在春季测试@Scheduled

时间:2013-06-26 18:40:01

标签: java spring unit-testing scheduler

Spring提供了使用注释以特定间隔安排和执行任务的可能性,例如: @Scheduled

是否有方便的方法对这种行为进行单元测试?

当然我可以自己调用bean的方法,但我想确保不会遇到像multiple executions due to misconfiguration等问题。

其他框架提供了自己快速转发时间的可能性。一个例子是Activiti,您可以在其中调用

org.activiti.engine.impl.util.ClockUtil.setCurrentTime(date)

快进框架使用的时间。

春天有可比的东西吗?

基本上我想要做的是在单元测试中使用SpringJUnit4ClassRunner运行

@Test public void testTaskScheduling() {

  assertThat(someOtherBean.getSomeProperty(), is(equalTo(whatIinitiallyExpect)));

  SpringClockUtil.setDate(dateInTwoHours)// This is what I am missing
  SpringTaskExecutor.executeAllScheduledTasks() // Also missing

  assertThat(someOtherBean.getSomeProperty(), is(equalTo(whatIexpectNow)));
}

2 个答案:

答案 0 :(得分:34)

您可以使用常规JUnit测试实际的方法执行,但要测试您指定的@Scheduled(cron = "0 * * * * *")是否正确,您可以使用:

@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);

}

这是输出:

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

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

由于最后一次执行(在TriggerContext中设置)是星期五,下一次执行将在下一个星期一执行。

我正在摆弄Spring api,我找到了这个解决方案,我希望这对帮助我的人有所帮助。

答案 1 :(得分:-2)

通过直接调用bean来测试预定代码。

然后通过以下方式测试调度配置:

1)在测试环境中部署代码,让它运行一段时间并检查日志和/或结果(假设计划代码执行一些记录和/或产生可见结果)。

2)使用<task: />命名空间将Spring XML配置中的调度配置外部化,并使用{{1注入单元测试特定的时间间隔/时间表(最好是短时间和频繁的,以便在单元/集成测试中使用) }}。然后在您的测试中验证在给定(短)时间内调用的计划代码(无论是模拟的还是真实的)适当的次数。