gpt4 book ai didi

spring - 在 Spring 测试中禁用 @EnableScheduling

转载 作者:IT老高 更新时间:2023-10-28 13:03:56 24 4
gpt4 key购买 nike

当我运行单元测试时,它会调用我的计划任务。我想防止这种行为,这是由于我的主应用配置中有 @EnableScheduling 造成的。

如何在我的单元测试中禁用它?

我遇到过这个question/answer这建议设置配置文件?

不确定我会怎么做?或者如果它是一个矫枉过正?我正在考虑为我的单元测试使用单独的 AppConfiguration,但是当我这样做时感觉就像我重复了两次代码?

@Configuration
@EnableJpaRepositories(AppConfiguration.DAO_PACKAGE)
@EnableTransactionManagement
@EnableScheduling
@ComponentScan({AppConfiguration.SERVICE_PACKAGE,
AppConfiguration.DAO_PACKAGE,
AppConfiguration.CLIENT_PACKAGE,
AppConfiguration.SCHEDULE_PACKAGE})
public class AppConfiguration {

static final String MAIN_PACKAGE = "com.etc.app-name";
static final String DAO_PACKAGE = "com.etc.app-name.dao";
private static final String ENTITIES_PACKAGE = "com.etc.app-name.entity";
static final String SERVICE_PACKAGE = "com.etc.app-name.service";
static final String CLIENT_PACKAGE = "com.etc.app-name.client";
static final String SCHEDULE_PACKAGE = "com.etc.app-name.scheduling";


@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
// stripped code for question readability
}

// more app config code below etc

}

单元测试示例。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfiguration.class})
@Transactional
@TransactionConfiguration(defaultRollback = true)
@WebAppConfiguration
public class ExampleDaoTest {

@Autowired
ExampleDao exampleDao;

@Test
public void testExampleDao() {
List<Example> items = exampleDao.findAll();
Assert.assertTrue(items.size()>0);
}
}

最佳答案

如果您不想使用配置文件,您可以添加标志以启用/禁用应用程序的调度

在你的 AppConfiguration 添加这个

  @ConditionalOnProperty(
value = "app.scheduling.enable", havingValue = "true", matchIfMissing = true
)
@Configuration
@EnableScheduling
public static class SchedulingConfiguration {
}

并在您的测试中添加此注释以禁用调度

@TestPropertySource(properties = "app.scheduling.enable=false")

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

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