How do I test @Scheduled
job tasks in my spring-boot application?
package com.myco.tasks; public class MyTask { @Scheduled(fixedRate=1000) public void work() { // task execution logic } }
How do I test @Scheduled job tasks in my spring-boot application? What do you want to test exactly? If you want to test that work() does what it's supposed to do, you can test it like any other method of any other bean: you create an instance of the bean, call the method, and test that it does what it's supposed to do.
Click on the task in Task Scheduler and hit Run toward the bottom of list of actions on the right pane. If Run, doesn't appear, go to the Settings tab of the task's properties and check the box that enables run on demand. Show activity on this post.
The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.
The schedulers do not start or stop. In the real world, it is necessary to stop and restart the scheduler without restarting the spring boot application. The ScheduledAnnotationBeanPostProcessor class allows you to programmatically start and stop the scheduler without having to restart the spring boot application.
If we assume that your job runs in such a small intervals that you really want your test to wait for job to be executed and you just want to test if job is invoked you can use following solution:
Add Awaitility to classpath:
<dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <version>3.1.0</version> <scope>test</scope> </dependency>
Write test similar to:
@RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @SpyBean private MyTask myTask; @Test public void jobRuns() { await().atMost(Duration.FIVE_SECONDS) .untilAsserted(() -> verify(myTask, times(1)).work()); } }
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