Как запустить @SpringBatchTest с движком junit5 jupiter - PullRequest
0 голосов
/ 24 марта 2020

Я перехожу по ссылке ниже для записи сквозного весеннего пакетного задания.

https://docs.spring.io/spring-batch/docs/current/reference/html/testing.html#endToEndTesting

Это говорит об аннотировании вашего класса теста с помощью @RunWith ( SpringRunner.class), которая является функцией Junit4, и мой тестовый пример работает нормально с использованием винтажного движка junit5.

Поскольку мои другие тестовые наборы, не связанные с пакетами, выполняются на движке jupiter, я хотел использовать его для своей цели завершить весенний пакетный тест. Если я заменим @RunWith (SpringRunner.class) на @ExtendWith (SpringExtension.class), я не смогу увидеть, чтобы ни одно из полей с автопроводкой было создано и имело нулевое значение. Я не могу понять, что происходит не так.

Любой указатель будет высоко оценен

Пример кода тестового примера junit

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.JobRepositoryTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.assertj.core.api.Assertions.assertThat;

@Slf4j
@Testcontainers
@SpringBatchTest
@SpringBootTest
@RunWith(SpringRunner.class)
//@ExtendWith(SpringExtension.class)
@ContextConfiguration(initializers = {BatchJobConfigTest.Initializer.class})
@Import({LiquibaseConfigprimary.class, LiquibaseConfigsecondary.class})
public class BatchJobConfigTest {

    @Container
    private static final PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:latest")
            .withDatabaseName("dummy-db")
            .withUsername("sa")
            .withPassword("sa");

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;
    @Autowired
    @Qualifier("primaryDatasource")
    private HikariDataSource primaryDatasource;
    @Autowired
    @Qualifier("secondaryDatasource")
    private HikariDataSource secondaryDatasource;
    @Autowired
    private SecondaryRepository secondaryRepository;   
    @Autowired
    private PrimaryRepository primaryRepository;
    @Autowired
    private JobRepositoryTestUtils jobRepositoryTestUtils;
    @Autowired
    private BatchConfigurer batchConfigurer;
    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @BeforeEach
    void setup() {
        secondaryRepository.deleteAll();
        primaryRepository.deleteAll();
    }

    @Test
    public void testJob() throws Exception {
        assertThat(primaryRepository.findAll()).hasSize(1);
        assertThat(secondaryRepository.findAll()).hasSize(0);
        JobExecution jobExecution = jobLauncherTestUtils.launchJob();
        assertThat(secondaryRepository.findAll()).hasSize(1);
        assertThat(jobExecution.getExitStatus().getExitCode()).isEqualTo("COMPLETED");
    }

    static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
            if (!postgreSQLContainer.isRunning())
                postgreSQLContainer.start();
            TestPropertyValues.of(
                    "spring.data.postgres.url=" + postgreSQLContainer.getJdbcUrl(),
                    "spring.data.postgres.username=" + postgreSQLContainer.getUsername(),
                    "spring.data.postgres.password=" + postgreSQLContainer.getPassword(),
                    "spring.data.postgres.host=localhost",
                    "spring.data.postgres.port=" + postgreSQLContainer.getFirstMappedPort(),
                    "spring.data.postgres.database=" + postgreSQLContainer.getDatabaseName()
            ).applyTo(configurableApplicationContext.getEnvironment());

            TestPropertyValues.of(
                    "spring.datasource-secondary.jdbc-url=" + postgreSQLContainer.getJdbcUrl(),
                    "spring.datasource-secondary.username=" + postgreSQLContainer.getUsername(),
                    "spring.datasource-secondary.password=" + postgreSQLContainer.getPassword(),
                    "spring.datasource-secondary.driver-class-name=org.postgresql.Driver"
            ).applyTo(configurableApplicationContext.getEnvironment());

        }
    }

}

1 Ответ

1 голос
/ 24 марта 2020

Вы можете просто избавиться от @RunWith(SpringRunner.class). Нет необходимости добавлять @ExtendWith(SpringExtension.class), потому что это уже добавлено @SpringBootTest - по крайней мере, в текущих версиях Spring Boot.

Затем вам нужно изменить:

import org.junit.Test;

в

import org.junit.jupiter.api.Test;

, потому что именно это указывает платформе JUnit запускать тесты Jupiter вместо тестов Vintage. Надеюсь, что это решит ваши проблемы.

...