BackEnd/Spring Batch

30. Spring Batch Test

hanseom 2022. 1. 14. 18:30
반응형

Spring Batch 4.1.x 이상 버전 (Boot 2.1) 기준

 

의존성 추가 (pom.xml)

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <scope>test</scope>
        </dependency>

 

@SpringBatchTest

  자동으로 ApplicationContext에 테스트에 필요한 여러 유틸 Bean을 등록해 주는 어노테이션

  • JobLauncherTestUtils: launchJob(), launchStep()과 같은 스프링 배치 테스트에 필요한 유틸성 메소드 지원
  • JobRepositoryTestUtils: JobRepository를 사용해서 JobExecution을 생성 및 삭제 기능 메소드 지원
  • StepScopeTestExecutionListener: @StepScope 컨텍스트를 생성해 주며 해당 컨텍스트를 통해 JobParameter 등을 단위 테스트에서 DI 받을 수 있음
  • JobScopeTestExecutionListener: @JobScope 컨텍스트를 생성해 주며 컨텍스트를 통해 JobParameter 등을 테스트에서 DI 받을 수 있음

 

JobLauncherTestUtils

  • @Autowired void setJob(Job job) // 실행할 Job을 자동으로 주입 받음, 한 개의 Job만 받을 수 있음 (Job 설정클래스를 한 개만 지정해야 함)
  • JobExecution launchJob(JobParameters jobParameters) // Job을 실행시키고 JobExecution을 반환
  • JobExecution launchStep(String stepName) // Step을 실행시키고 JobExecution을 반환

 

JobRepositoryTestUtils

  • List<JobExecution> createJobExecutions(String jobName, String[] stepNames, int count) // JobExecution 생성
  • void removeJobExecutions(Collection<JobExecution> list) // JobExecution 삭제

 

SimpleJobTest.java

package io.springbatch.springbatchlecture;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.*;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;

@SpringBatchTest // JobLauncherTestUtils, JobRepositoryTestUtils 등을 제공하는 어노테이션
@RunWith(SpringRunner.class)
@SpringBootTest(classes={SimpleJobConfiguration.class, TestBatchConfig.class})
// @SpringBootTest: Job 설정 클래스 지정, 통합 테스트를 위한 여러 의존성 빈들을 주입 받기 위한 어노테이션
public class SimpleJobTest {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void simple_job_테스트() throws Exception {

        // given
        JobParameters jobParameters = new JobParametersBuilder()
                .addString("requestDate", "20020101")
                .addLong("date", new Date().getTime())
                .toJobParameters();

        // when
//        JobExecution jobExecution = jobLauncherTestUtils.launchJob(jobParameters);
        JobExecution jobExecution = jobLauncherTestUtils.launchStep("step1");

        // then
        Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED);
        StepExecution stepExecution = (StepExecution)((List) jobExecution.getStepExecutions()).get(0);

        Assert.assertEquals(stepExecution.getCommitCount(), 11);
        Assert.assertEquals(stepExecution.getWriteCount(), 1000);
        Assert.assertEquals(stepExecution.getWriteCount(), 1000);
    }

    @After
    public void clear() throws Exception {
        jdbcTemplate.execute("delete from customer2");
    }
}

TestBatchConfig.java

package io.springbatch.springbatchlecture;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@EnableBatchProcessing // 테스트 시 배치환경 및 설정 초기화를 자동 구동하기 위한 어노테이션
// 테스트 클래스마다 선언하지 않고 공통으로 사용하기 위함
public class TestBatchConfig {
}

[전체 소스코드]

 

[참고자료]

인프런-스프링 배치 - Spring Boot 기반으로 개발하는 Spring Batch

반응형