gpt4 book ai didi

java - 在 Junit 测试中禁用 Spring @EnableScheduling

转载 作者:行者123 更新时间:2023-11-30 06:08:57 28 4
gpt4 key购买 nike

我想在 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 {
...
}

但是当我运行测试时任务仍然被触发..有什么方法可以在运行测试时停止执行任务吗?

最佳答案

由于您两次都在同一个包上使用@ComponentScan,因此 spring 似乎也在加载其他配置。

您可以使用一些配置文件来过滤它,例如将其添加到您的 PersistenceJPATestConfig

@Profile("test")

在你的 JUnit 类上添加这个注解,这样它将使用“测试”配置文件执行

@ActiveProfiles("test")

编辑:你的主配置也应该被分析,所以当它的配置文件不活动时它会被忽略,所以你应该在主配置类上添加另一个@Profile,其配置文件不同于“test”

关于java - 在 Junit 测试中禁用 Spring @EnableScheduling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033456/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com