目录
article
Spring Boot 项目中如何在运行 JUnit 时禁止 @EnableScheduling 的定时任务
Spring Boot 项目中如何在运行 JUnit 时禁止 @EnableScheduling 的定时任务
项目中使用了 Nacos 配置中心,如果当前启用的 profile 为 test ,则在应用启动时会查找名为 {application-name}-{active-profile}.{suffix} 的配置文件。基于此可以通过如下方案实现想要的效果。
将
@EnableScheduling移到单独的配置类,并添加@ConditionalOnProperty注解。@ConditionalOnProperty注解的name属性的值要和后面配置文件中的配置项一致。这里为scheduling.enabled,可以根据项目实际情况自定义。import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling @ConditionalOnProperty(name = "scheduling.enabled", havingValue = "true", matchIfMissing = true) public class SchedulingConfig { }在 Nacos 中添加 active profile 为 test 的配置文件
scheduling: enabled: false在测试类上通过添加
@ActiveProfiles("test")注解指定 active profiles 。@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) @Slf4j @ActiveProfiles("test") public class ThemeControllerTest { }另外,也可以通过在调试配置页面添加程序实参(
--spring.profiles.active=test)的方式来指定 active profiles 。程序实参前面的--如果少了会不起作用。