在测试期间调用计划的方法

nbr*_*bro 10 java testing scheduled-tasks spring-boot

我正在使用Maven开发SpringBoot应用程序.

我有一个带有@Component注释的类,它有一个m@Scheduled(initialDelay = 1000, fixedDelay = 5000)注释的方法.这里fixedDelay可以设置为指定从完成任务开始测量的调用之间的间隔.

我还在@EnableScheduling主类中注释:

@SpringBootApplication
@EnableScheduling
public class FieldProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(FieldProjectApplication.class, args);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在每当我运行测试时,定义为:

@RunWith(SpringRunner.class)
@SpringBootTest
public class BankitCrawlerTests {

...

}
Run Code Online (Sandbox Code Playgroud)

计划任务m也每5秒运行一次.

当然,我只想在应用程序运行时运行计划任务.我该怎么做(即阻止计划任务在运行测试时运行)?

Mac*_*iak 20

您可以提取@EnableScheduling到单独的配置类,如:

@Configuration
@Profile("!test")
@EnableScheduling
class SchedulingConfiguration {
}
Run Code Online (Sandbox Code Playgroud)

一旦完成,剩下的唯一事情就是通过使用以下方法注释测试类来激活测试中的"test"配置文件:

@ActiveProfiles("test")
Run Code Online (Sandbox Code Playgroud)

此解决方案的可能缺点是您使生产代码了解测试.

另外,您可以用性能发挥,而不是注释SchedulingConfiguration@Profile,你可以把它@ConditionalOnProperty与属性只存在于生产application.properties.例如:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Configuration
    @ConditionalOnProperty(value = "scheduling.enabled", havingValue = "true", matchIfMissing = true)
    @EnableScheduling
    static class SchedulingConfiguration {

    }
}
Run Code Online (Sandbox Code Playgroud)

当您执行以下操作之一时,调度程序将无法在测试中运行:

  • 将属性添加到src/test/resources/application.properties:

    scheduling.enabled = FALSE

  • 定制@SpringBootTest:

    @SpringBootTest(properties = "scheduling.enabled=false")