在Junit测试中禁用Spring @EnableScheduling

mar*_*ili 2 java junit spring spring-mvc

我想在Spring测试中禁用@Schedule,但我找不到办法.

我试图为测试环境制作不同的配置类,但仍然会触发任务.这是配置:

@Configuration
@EnableTransactionManagement
@EnableScheduling
@ComponentScan({"de.package"})
@PropertySource(name="application.properties", value="classpath:application.properties")
public class PersistenceJPAConfig {
...
}
Run Code Online (Sandbox Code Playgroud)

这是测试环境配置.刚删除@EnableScheduling注释

@Configuration
@EnableTransactionManagement
@ComponentScan({"de.package"})
@PropertySource(name="application.properties", value="classpath:application.properties")
public class PersistenceJPATestConfig {
...
}
Run Code Online (Sandbox Code Playgroud)

在测试我使用:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPATestConfig.class }, loader = AnnotationConfigContextLoader.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GetArticlesTest {
...
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时,任务仍然被解雇..有没有办法在运行测试时停止执行任务?

lep*_*pak 5

当你在同一个包上同时使用@ComponentScan时,似乎spring也在加载其他配置.

您可以使用某个配置文件来过滤它,就像在PersistenceJPATestConfig上添加它一样

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

在JUnit类上添加此注释,以便使用"test"配置文件执行它

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

编辑:您的主配置也应该进行分析,以便在其配置文件未激活时被忽略,因此您应该在主配置类上添加另一个@Profile,其配置文件不同于"test"