Chetan Kinger
Chetan Kinger

Reputation: 15212

Triggering Spring batch jobs in JUnit test cases

The Background :

I am currently working on an application that uses Spring Batch to read a set of files and cache the contents of the file in memory. The cached data is then used by the business logic layer that is divided into different classes, each performing a specific business functionality by using the data from the cache.

The requirement :

I have been assigned the task to unit test the business logic layer. Since the business logic layer assumes that the data will be available in the cache, I need a way to trigger the Spring batch job in my unit tests before I can test a business logic class.

The question :

I am thinking of writing a parent JUnit class that will be extended by all JUnit classes that test the business logic. This parent JUnit class will trigger the Spring batch job to load the cache in the setUp method.

  1. What would be the best way to trigger the Spring batch job in the parent JUnit class?

  2. Can my parent JUnit class in the src/test/java folder be able to access the Spring job context files in the src/main/resources/META-INF folder?

Note that the objective is to test the classes that will use the work done by Spring batch rather than testing Spring batch jobs itself.

Upvotes: 2

Views: 10905

Answers (1)

Michael Minella
Michael Minella

Reputation: 21463

To answer your specific questions:

  1. To launch a Spring Batch job from a JUnit test, we provide a JobLauncherTestUtils class. The class can be configured in your test context to launch the job it's associated with, then wired into your unit test. You can see specific examples in the Spring Batch Samples module here: https://github.com/spring-projects/spring-batch/tree/master/spring-batch-samples.

  2. I presume you're using maven in which case the test classes should have visibility into everything the regular classes do, so yes it should.

As a side note, if you're trying to unit test the business code, you may want to consider not running the batch job and testing the business code in isolation. If the goal is to perform an integration test of the entire system, then your approach makes sense.

Upvotes: 4

Related Questions