在Junit测试中禁用Spring @EnableScheduling

时间:2016-08-19 07:31:37

标签: java spring spring-mvc junit

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

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

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

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

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

在测试中我使用:

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

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

2 个答案:

答案 0 :(得分:5)

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

你可以使用一些配置文件对其进行过滤,就像在PersistenceJPATestConfig上添加它一样

var Ach1 = Achieve(node: SKSpriteNode?, aName: "No. Games", aDes: "Games Played", aImage: "locked", aAmount: 0, aRequired: 10)

在JUnit类上添加此注释,以便使用“test”配置文件

执行
@Profile("test")

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

答案 1 :(得分:0)

基于其他答案的快速解决方案(适用于Spring Boot用户),只需将以下代码添加到主要配置中,这样它就不会在测试配置文件和测试用例上运行!没有其他变化!

@Profile(!test)
public class Config{
......
}