Akashic Records

Spring Batch Tasklet 단위 테스트(Unit Test) 본문

Spring.io

Spring Batch Tasklet 단위 테스트(Unit Test)

Andrew's Akashic Records 2023. 4. 27. 15:28
728x90

Spring Batch Tasklet 단위 테스트를 위해서는 Tasklet 구현체를 직접 호출하여 실행하고 결과를 검증할 수 있습니다. 아래 예제를 참고해주세요.

1. 먼저, 간단한 Tasklet 구현체를 작성합니다:

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.repeat.RepeatStatus;

public class MyTasklet implements org.springframework.batch.core.step.tasklet.Tasklet {

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) {
        // Tasklet 로직을 작성합니다.
        System.out.println("Hello, Tasklet!");

        // 작업이 성공적으로 완료되었음을 나타내는 RepeatStatus를 반환합니다.
        return RepeatStatus.FINISHED;
    }
}


2. Tasklet 단위 테스트를 작성합니다:

import org.junit.jupiter.api.Test;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.repeat.RepeatStatus;

import static org.assertj.core.api.Assertions.assertThat;

public class MyTaskletTest {

    @Test
    public void testMyTasklet() {
        // Tasklet 인스턴스를 생성합니다.
        MyTasklet myTasklet = new MyTasklet();

        // StepContribution과 ChunkContext를 생성합니다.
        StepExecution stepExecution = new StepExecution("myTasklet", new JobExecution(1L));
        StepContribution stepContribution = new StepContribution(stepExecution);
        ChunkContext chunkContext = new ChunkContext(new StepContext(stepExecution));

        // Tasklet 실행
        RepeatStatus repeatStatus = myTasklet.execute(stepContribution, chunkContext);

        // Tasklet 실행 결과를 검증합니다.
        assertThat(repeatStatus).isEqualTo(RepeatStatus.FINISHED);
        assertThat(stepExecution.getExitStatus()).isEqualTo(ExitStatus.COMPLETED);
    }
}


이 예제에서는 MyTasklet 클래스의 인스턴스를 직접 생성하고, StepContribution과 ChunkContext를 설정하여 execute 메서드를 호출합니다. Tasklet 실행 결과를 검증하기 위해 반환된 RepeatStatus와 ExitStatus를 확인합니다. 이 방법을 사용하면 각 Tasklet의 동작을 독립적으로 테스트할 수 있습니다.

728x90
Comments