junit

Spring JUnit Test Example

In this example, I’ll be showcasing how to do Unit Tests for Spring beans using only annotations.

1. Introduction

Spring has its own testing framework for all objects created under its IOC container (that we all know is just the JVM instance). Spring has created its own paradigm of object creation and destruction and it made sense for it to have its own testing framework. The great thing about this is (as being Java) is it can be coupled with the core JUnit Testing framework, making it really easy to create JUnit Tests for its sources.

2. Maven POM

We need to include the following dependencies on our project. This will allow us to use Spring Test framework as well as the context package to allow us to inject our objects into our test cases.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.jgc.areyes.junit</groupId>
	<artifactId>junit-spring-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
	</dependencies>
</project>

3. The main class file

The following source is the main junit test case code of our example. As it can be seen here, we used annotation based context configuration. This approach allow developers to wire up their beans via Java classes instead of XML files.

JUnitSpringExample.java

package com.areyes1.jgc.junit.spring;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.BaseMatcher.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import com.areyes1.jgc.junit.spring.main.AppConfig;
import com.areyes1.jgc.junit.spring.service.SampleService;
import com.areyes1.jgc.unit.obj.Order;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class JUnitSpringExample {

	@Autowired
	private SampleService sampleService;


	@Test
	public void testSampleService() {
		assertEquals(
				"class com.areyes1.jgc.junit.spring.service.SampleServiceImpl",
				this.sampleService.getClass().toString());
	}

	@Test
	public void testSampleServiceGetAccountDescription() {
		// Check if the return description has a Description: string.
		assertTrue(sampleService.getOrderDescription().contains("Description:"));
	}

	@Test
	public void testSampleServiceGetAccountCode() {
		// Check if the return description has a Code: string.
		assertTrue(sampleService.getOrderStringCode().contains("Code:"));
	}

	@Test
	public void testSampleServiceCreateNewOrder() {
		Order newOrder = new Order();
		newOrder.setSecurityCode("XYZ");
		newOrder.setDescription("Description");
		if (newOrder != null) {
			assertThat(sampleService.createOrder(newOrder),
					instanceOf(Order.class));
			assertNotNull("Security isn't null", newOrder.getSecurityCode());
			assertNotNull("Description isn't not null",
					newOrder.getDescription());
		}

		assertNotNull("New Order is not null", newOrder);

	}

	@Test
	public void testSampleServiceGetOrder() {

		Order existingOrder = sampleService.getOrder(0);

		if (existingOrder != null) {
			assertThat(sampleService.getOrder(0), instanceOf(Order.class));
			assertNotNull("Security isn't null",
					existingOrder.getSecurityCode());
			assertNotNull("Description isn't null",
					existingOrder.getDescription());
		}

		assertNotNull("Object is not null", existingOrder);
	}

}

@RunWith – is an annotation to tag a class that this should Run with a specific runner class. There are a lot of alternative runners for JUnit but since we are using Spring test, we use: SpringJUnit4ClassRunner.class

@ContextConfiguration – Similar to calling the ClassPathContextConfiguration, this one is a pretty neat feature in Spring, especially in Unit test cases. It can be used to what type of ContextLoader for our class and the Java class files that we need to run on the ioc container (basically JVM) that are injectable on this class. For this case, we use AnnotationConfigContextLoader.class as our ContextLoader since we are creating a fully using annotation as our context metadata information and passed our AppConfig.class as our configuration stating point.

AppConfig.java

package com.areyes1.jgc.junit.spring.main;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.areyes1.jgc.junit.spring.service.SampleService;
import com.areyes1.jgc.junit.spring.service.SampleServiceImpl;

@Configuration
public class AppConfig {
	@Bean
	public SampleService getSampleService() {
		return new SampleServiceImpl();
	}
}

After implementing these 2 annotations, passing the correct context loader and configuration classes, we can now use Spring based annotation on our JUnit Test case classes. You can see this in action by looking at the class above when we injected the SampleService via wiring (@Autowired).

We then proceed with creating our JUnit Test cases for all specific method that the SampleService has (We need to include as much Junit Test case for each method as possible as this will greatly contribute to the coverage).

4. Output

spring test - Spring JUnit Example
Figure 1.0 Spring JUnit Example

5. Download the Eclipse project

This was an example of Spring JUnit Test.

Download
You can download the full source code of this example here: Spring JUnit Test Example

Last updated on Jun. 29th, 2021

Alvin Reyes

Alvin has an Information Technology Degree from Mapua Institute of Technology. During his studies, he was already heavily involved in a number of small to large projects where he primarily contributes by doing programming, analysis design. After graduating, he continued to do side projects on Mobile, Desktop and Web Applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button