Home  >  Spring 4

Spring 4 + JUnit 4 Annotation Example

By Arvind Rai, August 24, 2014
In 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.

Spring4JUnit4Test.java
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;

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

@RunWith(SpringJUnit4ClassRunner.class)

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

@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

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS





Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us