Spring Batch: почему модульный тест выполняет шаг дважды?

Я учусь модульному тестированию Spring Batch, но изо всех сил пытаюсь отладить случай, когда модульный тест дважды выполняет одно и то же задание Spring Batch.

Поскольку это мой первый модульный тест в Spring Batch, я попытался найти несколько рабочих примеров других модульных тестов Spring Batch для сравнения, но пока не нашел ничего, кроме руководства!

Проект модульного тестирования Spring Batch содержит точно такой же код, что и учебник Создание пакетной службы, со следующими исключениями:

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE")
    }
}

...

dependencies {
    compile("org.springframework.boot:spring-boot-starter-batch");
    compile("org.hsqldb:hsqldb");
    testCompile("junit:junit")
    testCompile("org.springframework.boot:spring-boot-starter-test");
    testCompile("org.springframework.batch:spring-batch-test");
}

И код модульного теста:

ПриложениеТест

package hello;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.assertEquals;

@SpringBatchTest
@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    public void testPersonJob() throws Exception {
        JobExecution jobExecution = jobLauncherTestUtils.launchJob();
        assertEquals("COMPLETED", jobExecution.getExitStatus().getExitCode());
    }

}

Журнал испытаний показывает, что задание завершается, как и ожидалось, при первом выполнении...

2019-05-05 20:30:33.808  INFO 28448 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] launched with the following parameters: [{run.id=1}]
2019-05-05 20:30:33.886  INFO 28448 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2019-05-05 20:30:34.011  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Jill, lastName = Doe) into (firstName: JILL, lastName = DOE)
2019-05-05 20:30:34.034  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Joe, lastName = Doe) into (firstName: JOE, lastName = DOE)
2019-05-05 20:30:34.034  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Justin, lastName = Doe) into (firstName: JUSTIN, lastName = DOE)
2019-05-05 20:30:34.034  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Jane, lastName = Doe) into (firstName: JANE, lastName = DOE)
2019-05-05 20:30:34.034  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: John, lastName = Doe) into (firstName: JOHN, lastName = DOE)
2019-05-05 20:30:34.049  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : !!! JOB FINISHED! Time to verify the results
2019-05-05 20:30:34.065  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JILL, lastName = DOE> in the database
2019-05-05 20:30:34.065  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JOE, lastName = DOE> in the database
2019-05-05 20:30:34.065  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JUSTIN, lastName = DOE> in the database
2019-05-05 20:30:34.065  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JANE, lastName = DOE> in the database
2019-05-05 20:30:34.065  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JOHN, lastName = DOE> in the database
2019-05-05 20:30:34.065  INFO 28448 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]

Но потом неожиданно почему-то то же самое задание выполняется снова:

2019-05-05 20:30:34.596  INFO 28448 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] launched with the following parameters: [{random=785577}]
2019-05-05 20:30:34.628  INFO 28448 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2019-05-05 20:30:34.659  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Jill, lastName = Doe) into (firstName: JILL, lastName = DOE)
2019-05-05 20:30:34.659  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Joe, lastName = Doe) into (firstName: JOE, lastName = DOE)
2019-05-05 20:30:34.659  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Justin, lastName = Doe) into (firstName: JUSTIN, lastName = DOE)
2019-05-05 20:30:34.659  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: Jane, lastName = Doe) into (firstName: JANE, lastName = DOE)
2019-05-05 20:30:34.674  INFO 28448 --- [           main] com.example.demo.PersonItemProcessor     : Converting (firstName: John, lastName = Doe) into (firstName: JOHN, lastName = DOE)
2019-05-05 20:30:34.690  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : !!! JOB FINISHED! Time to verify the results
2019-05-05 20:30:34.690  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JILL, lastName = DOE> in the database
2019-05-05 20:30:34.690  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JOE, lastName = DOE> in the database
2019-05-05 20:30:34.690  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JUSTIN, lastName = DOE> in the database
2019-05-05 20:30:34.690  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JANE, lastName = DOE> in the database
2019-05-05 20:30:34.690  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JOHN, lastName = DOE> in the database
2019-05-05 20:30:34.753  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JILL, lastName = DOE> in the database
2019-05-05 20:30:34.753  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JOE, lastName = DOE> in the database
2019-05-05 20:30:34.753  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JUSTIN, lastName = DOE> in the database
2019-05-05 20:30:34.753  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JANE, lastName = DOE> in the database
2019-05-05 20:30:34.753  INFO 28448 --- [           main] c.e.d.JobCompletionNotificationListener  : Found <firstName: JOHN, lastName = DOE> in the database
2019-05-05 20:30:34.753  INFO 28448 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] completed with the following parameters: [{random=785577}] and the following status: [COMPLETED]

Повторное выполнение происходит только при запуске ApplicationTest; выполнение приложения Spring Boot не воспроизводит проблему.

Вы используете JUnit 5 или 4?

nullptr 06.05.2019 01:11

JUnit 4.12, то есть последняя версия Репозиторий Maven, разрешенная сборкой Gradle на момент написания.

tjames6123 06.05.2019 10:39
0
2
1 096
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Spring автоматически запускает настроенные пакетные задания. Чтобы отключить автоматический запуск заданий, вам нужно использовать свойство spring.batch.job.enabled в файле application.properties.

spring.batch.job.enabled=false

Спасибо, теперь я вижу, что это причина, по которой задание выполняется дважды! Основываясь на вашем ответе, я заметил, что вызов jobLauncherTestUtils.launchJob() является ненужным кодом.

tjames6123 06.05.2019 10:51

Другие вопросы по теме