Testing @Scheduled in spring

谁说胖子不能爱 提交于 2019-11-28 16:58:42
Fernando Abreu

You can test the actual method execution using the regular JUnit, but to test if the @Scheduled(cron = "0 * * * * *") you specified is correct you can use:

@Test
public void testScheduler(){
    // to test if a cron expression runs only from Monday to Friday
    org.springframework.scheduling.support.CronTrigger trigger = 
                                      new CronTrigger("0 0 1 * * MON-FRI");
    Calendar today = Calendar.getInstance();
    today.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);

    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss EEEE"); 
    final Date yesterday = today.getTime();
    log.info("Yesterday was : " + df.format(yesterday));
    Date nextExecutionTime = trigger.nextExecutionTime(
        new TriggerContext() {

            @Override
            public Date lastScheduledExecutionTime() {
                return yesterday;
            }

            @Override
            public Date lastActualExecutionTime() {
                return yesterday;
            }

            @Override
            public Date lastCompletionTime() {
                return yesterday;
            }
        });

    String message = "Next Execution date: " + df.format(nextExecutionTime);
    log.info(message);

}

Here is the output:

Yesterday was : 2015/11/06 11:41:58 Friday

Next Execution date: 2015/11/09 01:00:00 Monday

As the last execution (set in the TriggerContext) was a Friday, the next execution will be on the following Monday.

I was fiddling with the Spring api and I found this solution, I hope this helps somebody as it helped me.

Test the scheduled code by invoking the bean directly.

Then test the scheduling configuration by:

1) deploying your code in a test environment, letting it run for a while and inspecting logs and/or results (assuming the scheduled code does some logging and/or produces visible results) afterwards.

or

2) externalizing the scheduling configuration in Spring XML config using the <task: /> namespace and injecting a unit test-specific interval/schedule (preferably short and frequent to be usable in a unit/integration test) using PropertyPlaceHolderConfigurer. Then in your test verify that the scheduled code (be it mocked or the real thing) was invoked the proper number of times in the given (short) amount of time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!