Spring JUnit How to Rollback Database Transaction

It’s common when you are testing your DAOs at a safe TDD environment to perform the DB action, assertThat what you’ve done is as expected and then safely rollback the transaction. All should look untouched at the DB level (except the DB sequences that are always moving forward) thereafter.

The annotations needed in the JUnit test class to achieve this are:

@ContextConfiguration(locations = "/pathTo/spring/context/applicationContext.xml")
@TransactionConfiguration(transactionManager = "jdbcTransactionManager", defaultRollback = true)
public class LocationDaoTest {
  @Inject daoInTest;
  public void testDAOsCRUD(){}


  • The ContextConfiguration annotation points to the main application’s context configuration file.
  • The TransactionConfiguration annotation points to your transaction manager defined in your application context which can either be a DataSourceTransactionManager for JDBC operations or a HibernateTransactionManager for Hibernate related ORM operations.
  • The defaultRollback=true attribute of the TransactionConfiguration is responsible for rolling back safely our test transactions.

Maven Integration Tests

Unit tests shouldn’t take long to complete and by definition should test a unit in isolation. Therefore unit tests shouldn’t include database or web framework resources.

Integration Testing is responsible putting everything together and check whether things work as expected. Maven has a special phase in its lifecycle called integration-tests that accommodates and executes integration related tests by calling mvn integration-test. A nice technique a colleague suggested is to have a name convention for integration tests and explicitly exclude/include during related phases in the Maven Surefire plugin. Assuming the naming convention referring to classes meant to be Integration Tests have the “IntegrationTest” suffix, the POM configuration of the maven-surefire-plugin would look something like this:


JUnit 4 Showcase – assertThat and Hamcrest Matchers

Surely assertEquals() can get you far but you will be amazed with the versatility of assertThat() combined with the expressive and human friendly Matchers of the Hamcrest library.

The needed static imports in your JUnit 4 test case:

import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;

You could use the is() and not() matchers like so:

	public void assertThat1(){
		double d = 1.3;
		assertThat(d, is(1.3));
		assertThat(d, is(not(1.4)));

or equalTo():

	public void assertThat2(){
		String str="test";
		assertThat(str, equalTo("test"));
		assertThat(str, not(equalTo("anotherTest")));

or anyOf():

	public void assertThat3(){
		String str="test";
		assertThat(str, anyOf(is("test"), is("this"), is("that")));
		assertThat(str, not(anyOf(is("tasty"), is("this"), is("that"))));

or lessThan() and hasItem() for Collections:

	public void assertThatCollections1(){
		List<String> list = new ArrayList<String>(){{add("one");add("two");add("three");}};
		assertThat(list, hasItem("two"));
		assertThat(list, not(hasItem("ttwo")));
	public void assertThatCollections2(){
		List<Integer> list = new ArrayList<Integer>(){{add(1);add(2);add(3);}};
		assertThat(list, not(hasItem(lessThan(0))));

or hasKey() and hasValue() particularly for Maps:

	public void assertThatMaps1(){
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("one", 1);
		map.put("two", 2);
		map.put("three", 3);
		assertThat(map, Matchers.<String,Integer>hasKey("one"));
		assertThat(map, Matchers.<String,Integer>hasValue(2));

A thing to note in the above example is the way we need to explicitly define the types on the key/value Map pair before summoning hasKey() or hasValue(), a bit weird why type inference didn’t help us there.

Finally we could even query properties of Java Beans:

	public void assertThatProperty1(){
		class Bean<T> {
			private T t;
			public void setT(T t){this.t = t;}
			public T getT(){return this.t;}
		Bean<String> myBean = new Bean<String>();
		assertThat(myBean, hasProperty("t",is("hi")));
		assertThat(myBean, hasProperty("t",startsWith("h")));

The code can be found in this Gitbub repository.

JUnit 4 Showcase – Parameterized Tests

A very interesting feature is the usage of parameterized tests to save us of the trouble of repetitive test code and automatically call test cases using predefined collection of test data.

Everything starts with the @RunWith(Parameterized.class) annotation that needs to be applied on the test class this time. A special public static method annotated as @Parameters signals the collection of test data. This set will be called by JUnit behind the scenes once per each data set calling the constructor for the creation of a new test class. The constructor should allocate this collection of test data into encapsulated members. These members would be used by the @Test annotated methods performing the test cases.

An example would look like this:

package com.dimitrisli.junitshowcase.parameterizedTest;

import java.util.Arrays;
import java.util.Collection;

import junit.framework.Assert;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

public class ParameterizedTesting {

	public static Collection<?> data(){
		return Arrays.asList(new Object[][]{
	private int a;
	private int b;
	private int result;
	public ParameterizedTesting(int a, int b, int result){
		this.a = a;
		this.b = b;
		this.result = result;
	public void multiplicationCalculation(){
		int calcResult = a*b;
		System.out.println("a="+a+", b="+b+". Expected result= "+result+", and calculated result= "+calcResult);
		Assert.assertEquals(result, calcResult);

that yields back the result:

a=2, b=3. Expected result= 6, and calculated result= 6
a=3, b=4. Expected result= 12, and calculated result= 12
a=4, b=5. Expected result= 20, and calculated result= 20
a=5, b=6. Expected result= 30, and calculated result= 30
a=6, b=7. Expected result= 42, and calculated result= 42

This code can be found in this Github repository.

JUnit 4 Showcase – testing exceptions

A nice way to determine we are expecting an exception during a test case is to use the @Test annotation with the expected parameter.

A trivial example would look like so:

package com.dimitrisli.junitshowcase.exceptionTesting;

import org.junit.Test;

public class ExceptionsTesting {

	@Test(expected = NullPointerException.class)
	public void method(){
		throw new NullPointerException();

	@Test(expected = IllegalArgumentException.class)
	public void method2(){
		throw new IllegalArgumentException();

This code extract along with the other examples of the JUnit 4 Showcase can be found in this Github repository.

JUnit 4 Showcase – Using timeouts

An interesting way to performance test the time it takes for an expensive operation to complete is to use JUnit 4’s timeouts. This way we can capture poor response times. In this case the test case fails if it takes longer than the predefined time in milliseconds to complete.

A trivial example would look like this:

package com.dimitrisli.junitshowcase.performanceTesting;

import org.junit.Test;

import junit.framework.Assert;

public class PerformanceTest {

	public void method(){

This code extract along with the full JUnit 4 showcase can be found in this Github repository.

JUnit 4 Showcase – Setting up and optimising unit tests

JUnit 4 has been a major rewrite of the JUnit API mainly:

  • it uses annotations
  • a test can be any POJO class, no need to extend TestCase or have special name conventions for test classes and methods. Although the main rules remain that each JUnit method needs to be public void and have no arguments.

In case we want to run initialisation code prior and post each test case (JUnit method) we can use the @Before and @After annotations saving us from the trouble of initialising the same code in each test case.

Similarly, if we need to run initialisation code prior and post every test class this time we can use the @BeforeClass and @AfterClass annotation. Other than these annotations, these particular methods need to be static.

Having as an example the following code:

package com.dimitrisli.junitshowcase.beforeAfter;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class BeforeAfterTest {

	public static void initialiseClass(){
		System.out.println("init class");
	public void initialiseTest(){
		System.out.println("init test");
	public void test1(){
		System.out.println("inside test1");

	public void test2(){
		System.out.println("inside test2");
	public void teardownTest(){
		System.out.println("teardown test");
	public static void teardownClass(){
		System.out.println("teardown class");

produces the output:

init class
init test
inside test1
teardown test
init test
inside test2
teardown test
teardown class

The code can be found in this Github repository.

TestNG Showcase – Unit Test Dependencies

A nice feature of TestNG that JUnit 4 is missing is the fact that it’s possible to specify unit tests that rely on other unit tests to complete first.

An example:

package com.dimitrisli.testng.dependents;

import org.testng.annotations.Test;

public class DependentMethodTesting {

	public void method2(){
		System.out.println("hi I am method2 and I depend on method1");
	public void method1(){
		System.out.println("hi I am method1");

that produces the output:

hi I am method1
hi I am method2 and I depend on method1

The code can be found in this Github repository.

TestNG Showcase – Parameterized Testing

The parameterized functionality is very helpful when it comes to group repetitive code for different input data.

We can do the following if we wanted to inject a parameter from a config file:

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My parameterized test suite">
  <test name="parameterised injection testing">
    <parameter name="i" value="13"/> 	
       <class name="com.dimitrisli.testng.parameterized.ParameterizedInjectionTest" />

to a unit test:

package com.dimitrisli.testng.parameterized;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterizedInjectionTest {

	public void method1(int i){
		System.out.println("inside method1() of parameterized example injected i = "+i);

@DataProvider is similar to JUnit 4’s @Parameters to inject values en masses, a trivial example would look like so:

package com.dimitrisli.testng.parameterized;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderTesting {

	public Object[][] parameterMethod(){
		return new Object[][]{{"one",1},{"two",2}};
	public void testMethod(String str, int val){
		System.out.println("str="+str+", val="+val);

A nice variation is to pass proper Java beans around:

package com.dimitrisli.testng.parameterized;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class AdvancedParameterizedTesting {

	public static class Bean{
		private String val;
		private int i;
		public Bean(String val, int i){
		public String getStr(){
			return this.val;
		public int getInt(){
			return this.i;
	@DataProvider(name = "advancedParameterizedMethod")
	public Object[][] advancedParameterizedMethod(){
		return new Object[][]{{new Bean("hi I am the bean",111)}};
	public void testMethod(Bean myBean){
		System.out.println(myBean.getStr()+" "+myBean.getInt());

The source code could be found in this Github repository.