在spring测试中禁用@EnableScheduling
当我运行单元测试时,它会调用我的计划任务。我想防止这种行为,这是由于我@EnableScheduling
在主应用程序配置中遇到的事实造成的。
如何在单元测试中禁用此功能?
不知道我该怎么做?还是过度杀伤力?我当时在考虑为单元测试使用一个单独的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测试中禁用@EnableScheduling 的全部内容, 来源链接: utcz.com/qa/433237.html