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?
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 }
Unit test example.
@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
In your AppConfiguration
add this
@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")
I just parameterized my @Scheduled annotation with configurable delay times:
@Scheduled(fixedRateString = "${timing.updateData}", initialDelayString = "${timing.initialDelay}")
In my test application.yaml:
timing: updateData: 60000 initialDelay: 10000000000
And main application.yaml:
timing: updateData: 60000 initialDelay: 1
It's not turning it off but creating such a long delay, the tests will be long over before it runs. Not the most elegant solution but definitely one of the easiest I've found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With