如何在java中使用CommandLineJobRunner构建多个集成测试用例



我正在使用SpringBatch的CommandLineJobRunner运行集成测试用例。如果我一个接一个地运行它,那么它运行得很完美,但当我通过清理和安装来构建它时,它并没有向前移动,它陷入了无限的等待中。

例如:正在运行作业,例如JobIT…

package job.eg;
import com.**;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ContextConfiguration(locations = { "classpath:*.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@TestPropertySource("classpath:application.properties")
public class EgJobIT {
@Autowired
@Qualifier(value="EG_JOB")
private Job job;
@Autowired
private JobLauncher jobLauncher;
@Autowired
private JobRepository jobRepository;
@Test
public void launchJob() throws Exception {
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
jobParametersBuilder.addString("legacy.date.format", "yyyyMMdd");
JobParameters jobParameters = jobParametersBuilder.toJobParameters();
String[] jobParamArr = MapUtil.mapToString(jobParameters);
String[] contextParam = new String[] { "file:src/test/resources/*.xml", "EG_JOB" };
String[] args = Stream.of(contextParam, jobParamArr).flatMap(Stream::of).toArray(String[]::new);
final Queue<Integer> exitCode = new ArrayBlockingQueue<Integer>(1);
CommandLineJobRunner.presetSystemExiter(new SystemExiter() {
@Override
public void exit(int status) {
exitCode.add(status);
}
});
//here it is calling main() method.
CommandLineJobRunner.main(args);
Assert.assertEquals(0, exitCode.poll().intValue());
}
}

N。B: 请考虑将*标记为某个类或配置文件名。

除非您不信任Spring Batch中的代码,否则我看不出在单元测试中使用CommandLineJobRunner的正当理由。

典型的作业单元测试使用JobLauncherJobLauncherTestUtils,如下所示:https://docs.spring.io/spring-batch/docs/4.2.x/reference/html/testing.html#testing

因此,在您的情况下,由于您正在测试类中注入作业和作业启动器,因此可以编写以下内容:

@Test
public void launchJob() throws Exception {
// given
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
jobParametersBuilder.addString("legacy.date.format", "yyyyMMdd");
JobParameters jobParameters = jobParametersBuilder.toJobParameters();
// when
JobExecution jobExecution = jobLauncher.run(job, jobParameters);
// then
Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}

最新更新