Skip to content

Spring Boot와 JUnit 테스트 Bean과 멤버변수 초기화 순서

moonyoung edited this page Jul 14, 2020 · 4 revisions

라빈과 타미의 삽질 공유기

JUnit5 @SpringBootTest에서 @Autowired 전에 멤버변수 초기화한다.

상황

KakaoProperties를 주입받는 KakaoPlaceCaller를 Test에서 사용하고자 함

(KakaoProperties, KakaoPlaceCaller : Bean)

기존 코드 (오류)

@SpringBootTest
class KakaoTest {
    @Autowired
    private KakaoProperties kakaoProperties; // (1)

    private KakaoPlaceCaller kakaoPlaceCaller = new KakaoPlaceCaller(kakaoProperties); // (2)
    
    
    @Test
    void test() {
        // do something
    }

기대한 실행 순서

(1) -> (2)

실제 실행 순서

(2) -> (1)

  • KakaoPlaceCaller에서 KakaoProperties이 null이여서 오류 발생

image

수정한 코드

@SpringBootTest
class KakaoTest {
    @Autowired
    private KakaoProperties kakaoProperties;
    private KakaoPlaceCaller kakaoPlaceCaller;
    
    @BeforeEach()
    void setUp() {
    	kakaoPlaceCaller = new KakaoPlaceCaller(kakaoProperties);
    }

혹은

@SpringBootTest
class KakaoTest {
    @Autowired
    private KakaoPlaceCaller kakaoPlaceCaller;
    ..
}

기타 참고
생성 순서: static -> 멤버변수 -> 생성자 -> @Autowired

Clone this wiki locally