Spring 통합 Junit 테스트 및 사무 설정

18522 단어 Spring
문제.
많은 경우 에 우 리 는 단원 테스트 결과 가 데이터 베 이 스 를 더 럽 히 는 것 을 원 하지 않 는 다. 우 리 는 인 육 을 더 럽 히 고 check 하 는 것 을 원 하지 않 는 다. 우 리 는 그것 이 흔적 없 이 조용히 집행 되 기 를 바란다. 나 에 게 최종 결 과 를 알려 주면 된다.그러면 어떻게 당신 의 UT 도 사무 기능 을 가지 게 합 니까?
예기 효과
우 리 는 이러한 효과 에 도달 할 수 있 기 를 바란다.
package me.arganzheng.study;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
/**
 *  
 * @author arganzheng
 */
public class FooServiceTest{
    @Autowired
    private FooService fooService;
    @Test
    @Rollback(true)
    public void testSaveFoo() {
        Foo foo = new Foo();
        // ...
        long id = fooService.saveFoo(foo);
        assertTrue(id > 0);
    }
}

비록 우리 가 데 이 터 를 삽입 하 였 지만, UT 이후 에는 이미 기러기 가 흔적 도 없 이 지나 갔다.
해결 방안
앞의 글 에서 JUnit 과 Spring 의 통합 인 JUnit 의 TestCase 가 Spring 용기 위탁 관리 대상 에 어떻게 자동 으로 주입 되 는 지 상세 하 게 소개 하 였 으 며, Spring 3 는 SpringJUnit4ClassRunner 기 류 를 제공 하여 JUnit 4 에 편리 하 게 접속 할 수 있 도록 하 였 다.
public class org.springframework.test.context.junit4.SpringJUnit4ClassRunner extends org.junit.runners.BlockJUnit4ClassRunner {
    ...
}

이벤트 감청 메커니즘 (the listener - based test context framework) 을 기반 으로 이벤트 감청 기 를 사용자 정의 할 수 있 습 니 다.기본 값 은 org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener 세 개의 사건 모니터 입 니 다.
이 중 org.springframework.test.context.support.DependencyInjectionTestExecutionListener 은 스프링 위탁 관 리 를 자동 으로 주입 하 는 bean 을 실현 한다.org.springframework.test.context.transaction.TransactionalTestExecutionListener 는 사무 관 리 를 실현 하 는 이벤트 프로세서 입 니 다.
org.springframework.test.context.transaction.TransactionalTestExecutionListener
TestExecutionListener which provides support for executing tests within transactions by using @Transactional and @NotTransactional annotations.
Changes to the database during a test run with @Transactional will be run within a transaction that will, by default, be automatically rolled back after completion of the test; whereas, changes to the database during a test run with @NotTransactional will not be run within a transaction. Similarly, test methods that are not annotated with either @Transactional (at the class or method level) or @NotTransactional will not be run within a transaction.
Transactional commit and rollback behavior can be configured via the class-level @TransactionConfiguration and method-level @Rollback annotations. @TransactionConfiguration also provides configuration of the bean name of the PlatformTransactionManager that is to be used to drive transactions.
When executing transactional tests, it is sometimes useful to be able execute certain set up or tear down code outside of a transaction. TransactionalTestExecutionListener provides such support for methods annotated with @BeforeTransaction and @AfterTransaction.
사실 나 는 Spring 의 javadoc 가 매우 간단명료 하고 전면적 이 며 다른 것 을 찾 아 다 닐 필요 가 없다 는 것 을 발견 했다. javadoc 와 소스 코드 를 직접 보면 된다.여기 서 간단하게 요약 하면:
  • TransactionalTestExecutionListener
  • @Transactional (class-level & method-level)
  • @NotTransactional (method-level)
  • @TransactionConfiguration (class-level)
  • @Rollback (method-level)
  • @BeforeTransaction (method-level)
  • @AfterTransaction (method-level)


  • 주: 그 중에서 class - level 즉 Target(ElementType.TYPE), method - level 즉 Target(ElementType.METHOD).
    이렇게 하면 우 리 는 다음 과 같이 설정 할 수 있다.
    ackage me.arganzheng.study;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.transaction.annotation.Transactional;  
    /**
     *  
     * @author arganzheng
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({
        "classpath:conf-spring/spring-dao.xml",
        "classpath:conf-spring/spring-service.xml",
        "classpath:conf-spring/spring-controller.xml"
    })
    @TransactionConfiguration(transactionManager="transactionManager") //  ,      
    @Transactionnal
    public class BaseSpringTestCase{
    }

    그리고 우리 의 FooServiceTest 는 이렇게 쓰 면 업무 처리 능력 을 가 질 수 있 습 니 다.
    package me.arganzheng.study;
    import static org.junit.Assert.*;
    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.annotation.Rollback;
    /**
     *  
     * @author arganzheng
     */
    public class FooServiceTest extends BaseSpringTestCase{
        @Autowired
        private FooService fooService;
        @Test
        // @Rollback(true)     true
        public void testSaveFoo() {
            Foo foo = new Foo();
            // ...
            long id = fooService.saveFoo(foo);
            assertTrue(id > 0);
        }
    }

    좋은 웹페이지 즐겨찾기