Spring + JUnit Annotation

By Arvind Rai, August 24, 2014
On this page we will learn that how to use JUnit 4 in Spring 4. We will learn it by example. Our example will use Spring 4 and Hibernate 4 and JUnit 4 will test the Dao methods. Find the code of test case. Then we will describe about all the annotations which are being used.

package com.concretepage;
import static org.junit.Assert.assertEquals;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import com.concretepage.config.AppConfig;
import com.concretepage.dao.IPersonDao;
import com.concretepage.entity.Person;

@ContextConfiguration(classes = AppConfig.class)
@TransactionConfiguration(defaultRollback = true)
public class Spring4JUnit4Test {
  private IPersonDao personDao;
  private HibernateTemplate  hibernateTemplate;
  public void savePersonTest(){
	  Person person = hibernateTemplate.get(Person.class, 1);
	  assertEquals("Ram", person.getName());


Spring provides SpringJUnit4ClassRunner that implements the functionality of JUnit4ClassRunner. JUnit4ClassRunner is provided by JUnit. In the demo @Test is provided by SpringJUnit4ClassRunner.

@ContextConfiguration(classes = AppConfig.class)

@ContextConfiguration annotation uses the application context being used in the application. In our case, we are using AppConfig.java for bean definition.


@Transactional annotation tells the test case that if transaction does not complete then revert other transactions.

@TransactionConfiguration(defaultRollback = true)

Suppose if transaction is completed successfully, and test case has finished the data testing and then if we want to remove it from database, then TransactionConfiguration annotation works. To achieve it defaultRollback must be true.

How to Run the Demo

To run the example, find the dependency classes from Spring 4 + Hibernate 4 + Gradle Integration Example using Annotation . You can also get complete example from link given on bottom. The extra required Jar dependency for Spring Test is the given spring boot.
compile  'org.springframework.boot:spring-boot-starter-test:1.1.5.RELEASE' 

Download Complete Source Code


©2024 concretepage.com | Privacy Policy | Contact Us