Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Spring @Scheduled

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      }  } 
like image 631
S Puddin Avatar asked Aug 31 '15 20:08

S Puddin


People also ask

How do I test a spring scheduler?

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.

How do you test scheduled tasks?

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.

What is @scheduled in spring?

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.

How do I start and stop a scheduler in spring boot?

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.


1 Answers

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());     } } 
like image 115
Maciej Walkowiak Avatar answered Sep 30 '22 21:09

Maciej Walkowiak