<aside> 👉 목차
</aside>
Eruna 프로젝트에서 알람기능을 개발했다.
이 알람이라는 특성상 테스트 코드를 작성하지 않고는 기능 테스트하기가 굉장히 번거로웠다.
SpringBatch 에서 알람들을 가져와 스케줄러에 등록하는데, 어떤 알람을 등록할지 필터링하는 속성이 바로 시간과 요일이다. 현재보다 이후 시간으로 등록됐고, 금일 요일에 해당하는 알람만 스케줄러에 등록해야 하기 때문이다.
즉, Spring Batch로 알람을 읽은 후 스케줄 등록하는 로직을 테스트하려면 db에서 직접 시간과 요일을 수기로 수정하고, 실행하고, 알람 울릴 때까지 기다리는 이 과정이 너무 너무 번거로웠다.
때문에 Spring batch로 읽어오는 알람들을 quartz scheduler에 넣고, 의도한 로직대로 실행되는지 확인하는 과정을 테스트코드로 자동화하기로 했다.
Spring Batch 테스트코드를 작성하는 것은 처음이다보니 공부가 필요했던 미숙한 개념들을 테스트 코드와 함께 다시 복기하기 위해 포스트를 작성한다.
SpringBatch 5.0을 써서 레퍼런스가 많이 부족했다.
흔히 말하는 ‘삽질’의 연속이었는데, 그 과정은 github 커밋들을 보면 바보 같은 행위들을 확인할 수 있다.
Spring Batch 5.0 docs를 보면 기본적인 테스트 코드가 있다.
//For JUnit 5, this annotation can be used without manually
//registering the SpringExtension since @SpringBatchTest
//is meta-annotated with @ExtendWith(SpringExtension.class). Here is an example:
@SpringBatchTest
@SpringJUnitConfig(MyBatchJobConfiguration.class)
public class MyBatchJobTests {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
@BeforeEach
public void setup(@Autowired Job jobUnderTest) {
this.jobLauncherTestUtils.setJob(jobUnderTest); // this is optional if the job is unique
this.jobRepositoryTestUtils.removeJobExecutions();
}
@Test
public void testMyJob() throws Exception {
// given
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
// when
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
// then
Assertions.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}