问题描述
运行单元测试时,它会调用我的计划任务.我想防止这种行为,这是由于我的主应用程序配置上有@EnableScheduling
导致的.
When I run my unit tests, it invokes my scheduled tasks. I want to prevent this behaviour, which is caused by the fact that I have @EnableScheduling
on my main app configuration.
如何在单元测试中禁用它?
How can I disable this on my unit tests?
我遇到了这个问题/答案,建议设置个人资料?
I have come across this question/answer which suggests setting up profiles?
不确定我会怎么做吗?还是过度杀伤力?我当时在考虑为我的单元测试使用一个单独的AppConfiguration,但是当我这样做时,感觉就像我重复了两次代码吗?
Not sure how I would go about that? or if its an overkill? I was thinking of having a separate AppConfiguration for my unit tests but it feels like im repeating code twice when I do that?
@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);
}
}
推荐答案
如果您不想使用配置文件,则可以添加用于启用/禁用应用程序调度的标志
If you don't want to use profiles, you can add flag that will enable/disable scheduling for the application
在您的AppConfiguration
中添加此
@ConditionalOnProperty(
value = "app.scheduling.enable", havingValue = "true", matchIfMissing = true
)
@Configuration
@EnableScheduling
public static class SchedulingConfiguration {
}
在您的测试中,只需添加此注释即可禁用计划
and in your test just add this annotation to disable scheduling
@TestPropertySource(properties = "app.scheduling.enable=false")
这篇关于在春季测试中禁用@EnableScheduling的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!