如何测试 Spring @Scheduled [英] How to test Spring @Scheduled

查看:39
本文介绍了如何测试 Spring @Scheduled的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何测试 @Scheduled 我的 spring-boot 应用程序中的工作任务?

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
     }
 }

推荐答案

如果我们假设您的作业以如此小的间隔运行,以至于您真的希望您的测试等待作业执行而您只想测试作业是否执行被调用,您可以使用以下解决方案:

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:

Awaitility 添加到类路径:

<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());
    }
}

这篇关于如何测试 Spring @Scheduled的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆