【问题标题】:How can I prevent my Spring Boot Batch application from running when executing test?如何防止我的 Spring Boot Batch 应用程序在执行测试时运行?
【发布时间】:2016-04-26 22:40:11
【问题描述】:

我有一个正在编写集成测试的 Spring Boot Batch 应用程序。当我执行测试时,整个批处理应用程序都会运行。如何只执行被测应用程序代码?

这是我的测试代码。当它执行时,整个批处理作业步骤会运行(读取器、处理器和写入器)。然后,测试运行。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BatchApplication.class))
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        StepScopeTestExecutionListener.class })
public class StepScopeTestExecutionListenerIntegrationTests {

    @Autowired
    private FlatFileItemReader<String> reader;

    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();

    public StepExecution getStepExection() {
        StepExecution execution = MetaDataInstanceFactory.createStepExecution();
        return execution;
    }

    @Test
    public void testGoodData() throws Exception {
       //some test code on one met
       File testFile = testFolder.newFile();

       PrintWriter writer = new PrintWriter(testFile, "UTF-8");
       writer.println("test");
       writer.close();
       reader.setResource(new FileSystemResource(testFile));
       reader.open(getStepExection().getExecutionContext());
       String test = reader.read();
       reader.close();
       assertThat("test", equalTo(test));
    }
}

【问题讨论】:

    标签: java spring spring-boot spring-batch spring-test


    【解决方案1】:

    尝试使用以下内容在测试资源(例如 src/main/resources)中创建 application.properties 文件:

    spring.batch.job.enabled=false
    

    您需要确保集成测试读取。为此,您可能需要以这种方式使用ConfigFileApplicationContextInitializer

    @SpringApplicationConfiguration(classes = TestApplication.class, 
             initializers = ConfigFileApplicationContextInitializer.class)
    

    【讨论】:

    • 应用程序已经在使用 /src/main/resources/application.yml。有没有办法指向不同的配置文件进行测试?
    • 除了把一个放在src/test/resources?
    • 是的,我尝试将它放在 src/test/resources 中。现在,该作业在测试和常规应用程序运行期间被禁用。
    • 我向 /src/main/resources/application.yml 添加了另一个配置文件。在该配置文件中,我设置了 spring.batch.job.enabled=false。然后,通过@ActiveProfiles 将其设置为集成测试类的活动配置文件。因此,连同您在回答中提到的内容似乎可以满足我的需要(即在集成测试期间不要运行批处理作业。在应用程序运行期间运行批处理作业)。
    • 这很奇怪。测试资源不应包含在生产工件中。你用的是 maven 还是 gradle?
    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2016-04-25
    • 2021-05-28
    • 2019-05-02
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多