简体   繁体   中英

How to write test case in spring batch if job is running with simpleAsyncTaskExecutor

I have spring batch job which is running with SimpleAsyncTaskExecutor. I have to implement a test case for a Job. But Afterjob still executed after the completion of the test.

In my test case, I have an infinite loop where I am checking that Job execution is running or not. When it is completed I am checking for assert.

@Test
public void testPostalJob_valid_response() throws Exception {
    String fileName = getFileName(FileLocation.POSTAL_VALID, FileLocation.TEMP_POSTAL_VALID);
    JobParametersBuilder jobParametersBuilder = getJobParametersBuilder(fileName);
    new NonStrictExpectations () {
        {
            mailSender.send((SimpleMailMessage) any);
        }
    };
    jobLauncherTestUtils.setJob(postalJob);
    jobLauncherTestUtils.setJobLauncher(dataloadJobLauncher);
    JobExecution jobExecution = jobLauncherTestUtils.launchJob(jobParametersBuilder.toJobParameters());
    Assert.assertEquals(jobExecution.getStatus(), BatchStatus.STARTING);
    Thread.sleep(2000);
    while (jobExecution.isRunning()) {

    }
    Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED);
}

I want to test that job is completed or failed successfully, but I want it after the running of the main application. Right now I am using while loop but I want to use more cleaner way for async code. Please help me out for same.

The best solution that I got is to run the asynchronous job in the synchronous mode because here the main idea is to test that job is running successfully or not.

In the application, If JobLauncher name is not jobLauncher then you have to do nothing otherwise, you have to create jobLauncher and set into jobLauncherTestUtils.

@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;

@Autowired
private Job postalJob;

@Autowired
private MailServiceImpl mailService;


@BeforeClass
public void setJob() {
    jobLauncherTestUtils.setJob(postalJob);
    mailService.setMailSender(new JavaMailSenderTestImpl());
}

@Test
public void testPostalJob_valid_response() throws Exception {
    String fileName =
            TestUtil.getFileName(FileLocation.POSTAL_VALID, FileLocation.TEMP_POSTAL_VALID);
    JobParametersBuilder jobParametersBuilder = TestUtil.getJobParametersBuilder(fileName);
    JobExecution jobExecution =
            jobLauncherTestUtils.launchJob(jobParametersBuilder.toJobParameters());
    Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM