Kavau
Kavau

Reputation: 529

Spring Batch Tests

Read a few blogs on testing spring batch and set up a test accordingly (see below). The test completes. However, I have two questions:

  1. How can I be sure the assertion of the job status is not too early? The job starts asynchronously afaik. It could be it is not ready yet when the assert starts.
  2. After the job has finished I would like to do some assertions. However, the client (i.e. test) and server run in two different threads. If I understand it correctly then I would have to query via a JdbcTemplate or implement a query possibility on the server e.g. via rest (which then would be productive code). Is that correct? Are there other possibilities?

Testcode:

@SpringBootTest
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FooJobTest {

  @Inject
  private Job fooBatchJob;

  @Inject
  private JobLauncher jobLauncher;

  private JobLauncherTestUtils jobLauncherTestUtils;

  @Before
  public void setUp() {
    jobLauncherTestUtils = new JobLauncherTestUtils();
    jobLauncherTestUtils.setJob(fooBatchJob);
    jobLauncherTestUtils.setJobLauncher(jobLauncher);
  }

  @Test
  public void testFooJob() {
    final JobExecution jobExecution = jobLauncherTestUtils.launchJob();

    assertThat(jobExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED);

    // would like to query the database
  }
}

Upvotes: 2

Views: 226

Answers (1)

Michael Minella
Michael Minella

Reputation: 21463

To answer your questions:

  1. How can I be sure the assertion of the job status is not too early? - The JobLauncher uses the TaskExecutor you have configured which, by default, is a synchronous one. That being said, if you are using any of the asynchronous TaskExecutor implementations, you'd have to poll for the results (or add a JobExecutionListener to alert that it is complete).
  2. After the job has finished how do I query the database to make assertions? - I would just use JdbcTemplate to query and validate your data. Adding REST APIs to your server application just for use in test probably is a bad idea IMHO.

Upvotes: 2

Related Questions