Skip to content

Commit 1796e21

Browse files
MandroideBuzzardo
authored andcommitted
Add a spring batch job test
This is a good template to create batch job tests in JUnit.
1 parent 3cf93a3 commit 1796e21

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.example.batchprocessing;
2+
3+
import org.junit.jupiter.api.AfterEach;
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.BeforeEach;
6+
import org.junit.jupiter.api.Test;
7+
import org.springframework.batch.core.ExitStatus;
8+
import org.springframework.batch.core.Job;
9+
import org.springframework.batch.core.JobExecution;
10+
import org.springframework.batch.test.JobLauncherTestUtils;
11+
import org.springframework.batch.test.JobRepositoryTestUtils;
12+
import org.springframework.batch.test.context.SpringBatchTest;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.boot.test.context.SpringBootTest;
15+
import org.springframework.test.annotation.DirtiesContext;
16+
import org.springframework.test.context.ActiveProfiles;
17+
import org.springframework.test.context.TestExecutionListeners;
18+
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
19+
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
20+
21+
@ActiveProfiles("test")
22+
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
23+
DirtiesContextTestExecutionListener.class})
24+
// This is to avoid clashing of several JobRepository instances using the same data source for several test classes
25+
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
26+
@SpringBatchTest
27+
@SpringBootTest // This is required to be able to used spring boot features such as profiles
28+
class BatchConfigurationTest {
29+
30+
@Autowired
31+
private JobLauncherTestUtils jobLauncherTestUtils;
32+
@Autowired
33+
private JobRepositoryTestUtils jobRepositoryTestUtils;
34+
@Autowired
35+
private Job importUserJob;
36+
37+
@BeforeEach
38+
void setUp() {
39+
jobLauncherTestUtils.setJob(importUserJob);
40+
}
41+
42+
@AfterEach
43+
void tearDown() {
44+
jobRepositoryTestUtils.removeJobExecutions();
45+
}
46+
47+
@Test
48+
void importUserJob_WhenJobEnds_ThenStatusCompleted() throws Exception {
49+
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
50+
Assertions.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
51+
}
52+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
spring:
2+
batch:
3+
job:
4+
enabled: false

0 commit comments

Comments
 (0)