Spring Boot 项目中如何在运行 JUnit 时禁止 @EnableScheduling 的定时任务

项目中使用了 Nacos 配置中心,如果当前启用的 profile 为 test ,则在应用启动时会查找名为 {application-name}-{active-profile}.{suffix} 的配置文件。基于此可以通过如下方案实现想要的效果。

  1. @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 {
    
    }
      
  2. 在 Nacos 中添加 active profile 为 test 的配置文件

    scheduling:
      enabled: false
      
  3. 在测试类上通过添加 @ActiveProfiles("test") 注解指定 active profiles

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = RANDOM_PORT)
    @Slf4j
    @ActiveProfiles("test")
    public class ThemeControllerTest {
    
    }
      

    另外,也可以通过在调试配置页面添加程序实参(--spring.profiles.active=test)的方式来指定 active profiles 。程序实参前面的 -- 如果少了会不起作用。