기본 콘텐츠로 건너뛰기

Spring Boot + Spring Batch 그리고 CommandLineRunner Unit 테스트 하기

커멘드라인에서 실행되는 배치 어프리케이션을 작성할때 겪었던 2가지 문제 정리

첫번째, 커멘드라인에서 실행하는 배치프로그램을 만들때 spring.batch.job.enabled 옵션을 꺼두지 않아 Job이 두번 실행되는 문제

http://stackoverflow.com/questions/23447948/how-spring-boot-run-batch-jobs
http://stackoverflow.com/questions/22318907/how-to-stop-spring-batch-scheduled-jobs-from-running-at-first-time-when-executin

spring.batch.job.enabled: false


두번째, 부트기반 커멘드라인 어프리케이션은 UnitTest를 작성하기가 불편하기 때문에 CommandLineRunner 인터페이스를 사용했다. 이 CommandLineRunner는 스프링 빈이 모두 생성 후 호출되어 Unit Tese 작성이 수월하다.

문제는 Unit Test를 설정에 @SpringApplicationConfiguration 을 사용하면 CommandLineRunner가 바로 실행 되어 버린다. CommandLineRunner가 여러개일 경우나 인자를 넘겨야 할 때는 문제가 된다. @SpringApplicationConfiguration은 단순히 SpringApplicationConfiguration Loader를 @ContextConfiguration로 사용하는 어노테이션이다. ( 코드 )

...

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
public class AppTest {

  @Test public void test1() { ... }
}

...

그래서 @ContextConfiguration 에 class를 지정하면 CommandLineRunner가 바로 실행되지 않게 할 수 있다.

...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = App.class)
public class AppTest {

  @Test public void test1() { ... }
}

...

이렇게 설정하고 CommandLineRunner를 ApplicationContext에서 찾아 인자와 함께 실행시키면 된다.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = App.class)
public class AppTest {

    @Autowired
    ApplicationContext context;

    @Test
    public void execCommandLineRunner() throws Exception {
        App.SimpleCommandLineRunner runner
                = context.getBean(App.SimpleCommandLineRunner.class);
        runner.run(new String[]{});
    }
}


전체 코드는 여기..




댓글