Home » Java » Enterprise Java » Spring 3 Testing with JUnit 4 – ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests

About Ioannis Dadis

Spring 3 Testing with JUnit 4 – ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests

Looking in the internet for a way to test my Spring 3 application, I found many articles that describe how to test your application by using JUnit. Most of them are incomplete examples that do not really work.

With this article I will try to fill this gap and write a concise yet simple article on how to test a spring 3 application with Junit 4. Ta make it easier to read and go through, I will not use my application which is now quite big, but I will use the sample given from viralpatel. The link to download the project is this.

Download this application and import it into eclipse.

Execute the following in you db:

create database contact;
use contact;
    firstname    VARCHAR(30),
    lastname    VARCHAR(30),
    telephone   VARCHAR(15),
    email         VARCHAR(30),
    created     TIMESTAMP DEFAULT NOW()

Inside your pom.xml add the following dependencies:

<dependency> <groupId>javax.transaction</groupId>

Also add the following for repositories:

  <name>SpringSource Enterprise Bundle Repository - SpringSource Releases</name>
  <name>SpringSource Enterprise Bundle Repository - External Releases</name>
  <name>SpringSource Enterprise Bundle Repository - SpringSource Milestones</name>
  <name>SpringSource Enterprise Bundle Repository - Snapshot Releases</name>
  <name>Spring Framework Maven Release Repository</name>
  <name>Spring Framework Maven Milestone Repository</name>
  <name>Spring Framework Maven Snapshot Repository</name>
  <name>JBoss repository</name>

Under the directory src/test/java create the following package:

Inside the package you just created create a class called:

Under src/test/resources create the following:

Inside there create the following file:

Attention! Make sure that the directories, packages, classes and xml files are created exactly where mentioned above. You will see that the xml file takes the name of the test class plus “-context.xml” and that it is created under the same directory structure. This is important because spring automatically looks for the xml file with the specified name and also under the same directory.

Now insert the following content in the AbstractContactTests class:

package net.viralpatel.contact.form;

import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.service.ContactService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

public class AbstractContactTests extends AbstractTransactionalJUnit4SpringContextTests {
 protected ContactDAO contact;
 protected ContactService contactService;
 public void sampleTest(){
   System.out.println("Number of rows is: " + contactService.listContact().size());
  System.out.println("Creating a new contact");
  Contact cont = new Contact();
  cont.setEmail("[email protected]");
  System.out.println("Before saving contact");
  System.out.println("After saving contact. Id if contact is: " + cont.getId());
  System.out.println("Number of rows now is: " + contactService.listContact().size());

The @ContextConfiguration annotation tells spring how to load and configure the application context. We could also tell spring where it would explicitly find the file, e.g. :

@ContextConfiguration(locations={“example/test-context.xml”}, loader=CustomContextLoader.class)

By providing no parameters, spring will look for the xml file under the same directory as the package of the class, and for a file named class.name-context.xml (remember the HINT above).

Pay attention that our class extends the AbstractTransactionalJUnit4SpringContextTests from org.springframework.test.context.junit4. By extending this class, we give our methods transactional support at the class level. If we did not do this, and we wanted transactional support, we would have to either annotate our methods with @Transactional or configure our transaction manager with the @TransactionConfiguration annotation.

Inside the AbstractContactTests-context.xml put the following content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
 <context:property-placeholder location="classpath:jdbc.properties"/>
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
   p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/contact"
   p:username="root" p:password="123456"/>
 <bean id="sessionFactory"
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation">
  <property name="configurationClass">
  <property name="hibernateProperties">
    <prop key="hibernate.dialect">${jdbc.dialect}</prop>
    <prop key="hibernate.show_sql">true</prop>
 <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 <bean id="contactDAO" class="net.viralpatel.contact.dao.ContactDAOImpl"></bean>
 <bean id="contactService" class="net.viralpatel.contact.service.ContactServiceImpl"></bean>

Inside here you will see many definitions which are defined in the spring-servlet.xml. In my example they are the same with spring-servlet.xml, but you could freely alter them. With this, Spring gives the opportunity to create a different data source for example, for the testing process, or even different data source for each test class.

Now execute the AbstractContactTests class as a junit test. You should take the following output:

Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows is: 0
Creating a new contact
Before saving contact
Hibernate: insert into CONTACTS (EMAIL, FIRSTNAME, LASTNAME, TELEPHONE) values (?, ?, ?, ?)
After saving contact. Id if contact is: 2
Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows now is: 1

Thats all you need folks. Happy coding and don’t forget to share!

Reference: Spring 3 Testing with JUnit 4. Using @ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests from our JCG partner Ioannis Ntantis at the Giannisapi blog.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....




  1. Javier Alcalá Vásquez

    Thank you, good article.

  2. very good article bro thanks

  3. Hi Thanks for this example, How can we do this with jpa transaction manager

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns