ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JUnit] @RunWith, @ContextConfiguration 그리고 @SpringApplicationConfiguration
    Java/JUnit 2017. 1. 8. 20:59


    스프링 JUnit 테스트를 할 때 테스트 클래스 상단에 @RunWith(SpringJUnit4ClassRunner.class)와 @Contextconfiguration({applicationContext 경로})나 @SpringApplicationConfiguration({Config 경로})를 설정해준다.


    그냥 따라하면 되긴하지만 왜 그렇게 되는지 궁금하여 찾아봤다.



    1. @RunWith javac

    When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit. 


    2. 토비의 스프링 3.1 Vol1 2장 테스트 p.185, 186

      @RunWith는 JUnit 프레임워크의 테스트 실행 방법을 확장할 때 사용하는 애노테이션이다. SpringJUnit4ClassRunner라는 JUnit용 테스트 컨텍스트 프레임워크 확장 클래스를 지정해주면 JUnit이 테스트를 진행하는 중에 테스트가 사용할 애플리케이션 컨텍스트를 만들과 관리하는 작업을 진행해준다.

      @ContextConfiguration은 자동으로 만들어줄 애플리케이션 컨텍스트의 설정파일위치를 지정한 것이다.


      스프링의 JUnit 확장기능은 테스트가 실행되기 전에 딱 한 번만 애플리케이션 컨텍스트를 만들어두고, 테스트 오브젝트가 만들어질 때마다 특별한 방법을 이용해 애플리케이션 컨텍스트 자신을 테스트 오브젝트의 특정 필드에 주입해주는 것이다.


    정리해보자면 @RunWith에 Runner클래스를 설정하면 JUnit에 내장된 Runner대신 그 클래스를 실행한다. 여기서는 스프링 테스트를 위해서 SpringJUnit4ClassRunner라는 Runner 클래스를 설정해 준 것이다.

    한 클래스내에 여러개의 테스트가 있더라도 어플리케이션 컨텍스트를 초기 한번만 로딩하여 사용하기 때문에, 여러개의 테스트가 있더라도 처음 테스트만 조금 느리고 그 뒤의 테스트들은 빠르다.



    추가로 @ContextConfiguration@SpringApplicationConfiguration를 비교


    @ContextConfiguration의 locations 속성에는 xml형태의 애플리케이션 컨텍스트만 로딩 가능한 것 같다(class파일을 지정하니 오류 발생)

      ex)

    @ContextConfiguration(locations="applicationContext.xml")
    


    @SpringApplicationConfiguration은 Spring Boot에서 class형태의 애플리케이션 컨텍스트를 로딩 할 수 있는것 같다.

      ex)

    @SpringApplicationConfiguration(classes = App.class)
    




    댓글

Designed by Tistory.