How to test Spring @Scheduled
我如何测试我的spring-boot应用程序的Scheduled / cron作业任务?
package com.myco.tasks;
public class MyTask {
@Scheduled(fixedRate=1000)
public void work() {
// task execution logic
}
}
This is often hard. You may consider to load Spring context during the test and fake some bean from it to be able to verify scheduled invocation.
I have such example in my Github repo. There is simple scheduled example tested with described approach.
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());
}
}
链接地址: http://www.djcxy.com/p/28580.html