我如何测试 @Scheduled
我的 spring-boot 应用程序中的工作任务?
package com.myco.tasks;
public class MyTask {
@Scheduled(fixedRate=1000)
public void work() {
// task execution logic
}
}
最佳答案
如果我们假设您的作业以如此小的间隔运行,您真的希望您的测试等待作业被执行并且您只想测试是否调用了作业,您可以使用以下解决方案:
添加 Awaitility到类路径:
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.0</version>
<scope>test</scope>
</dependency>
编写类似的测试:
@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());
}
}
关于java - 如何测试 Spring @Scheduled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32319640/