How to pass JobParameters to the Spring Batch Junit Test case JobLauncherTestUtils?

user5778069 picture user5778069 · Jan 23, 2017 · Viewed 8.5k times · Source

I am newbie to the Spring Batch, I have a following main program which I want to convert it into the test case using jobLauncherTestUtils. How we can do that?

I followed http://docs.spring.io/spring-batch/reference/html/testing.html, but I don't see any pointers. Please guide.

private void run() {
        String[] springConfig = { "spring/batch/jobs/job-extract-users.xml" };
        ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

        JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
        Job job = (Job) context.getBean("testActualJob");

        try {
            JobParameters param = new JobParametersBuilder().addString("age", "20").toJobParameters();

            JobExecution execution = jobLauncher.run(job, param);
            System.out.println("----------------------------------------------");
            System.out.println("Exit Status : " + execution.getStatus());
            System.out.println("Exit Status : " + execution.getAllFailureExceptions());
            System.out.println("-----------------------------------------------");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Done !!");
    } 

Answer

Amit Bhati picture Amit Bhati · Jan 23, 2017

Quoted from the documentation:-

The launchJob() method is provided by the JobLauncherTestUtils class. Also provided by the utils class is launchJob(JobParameters), which allows the test to give particular parameters.

Your code will look like below:-

JobParameters param = new JobParametersBuilder().addString("age", "20").toJobParameters();
 JobExecution jobExecution = jobLauncherTestUtils.launchJob(param).getStatus();