JUnit 4.x with Spring-test Module

Spring-JUnit 테스트시 applicationContext를 @Annotation을 통해 간편하게 로딩하고 초기화하기 위한 Spring Module로써, Spring TestContext Framework라고도 한다.
기존 Spring의 TestClass들을 상속하여 직접 ApplicationContext를 통해 Bean을 스캔하는 방법보다 훨씬 심플하며 직관적이고 추상화하기도 좀 더 편하다.

현재일자 기준으로 최신 버전은 3.0.5이다.

1. Maven POM

<!-- Spring-test Module -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>3.0.5.RELEASE</version>
</dependency>
 
...
 
<!-- JUnit -->
<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.8<version>
   <scope>test</scope>
</dependency>

2.1 Test - Pure JUnit

import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.xenomity.service.PersonService;
 
/*
 * Test JUnit
 */
public class PersonTest {
    private PersonService personService;
 
    @Before
    public void before() {
        BeanFactory factory = new XmlBeanFactory(new ClassPathResource("classpath:/applicationContext.xml"));
 
        personService = (PersonService) factory.getBean("personService");
 
    }
 
    @Test
    public void test() { ... }
 
}

2.2 Test - TestContext

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.xenomity.service.PersonService;
 
/*
 * Test JUnit
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/applicationContext.xml")
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)
@Transaction
public class PersonTest {
 
    @Autowired
    private PersonService personService;
 
    @Test
    public void test() { ... }
 
}

Comments