繁体   English   中英

为什么石英示例代码无法在 Junit 中测试?

[英]why quartz example code can't be tested in Junit?

I am running this quartz-2.1.0\examples\src\main\java\org\quartz\examples\example3 sample code, it runs very well, but if I move the main code in CronTriggerExample.java to a junit test class,作业没有运行。 以下是石英示例代码(为简化起见,我将它们截断,您可以从石英网站获取完整代码)。

SimpleJob.java:

public class SimpleJob implements Job {
  private static Logger _log = LoggerFactory.getLogger(SimpleJob.class);

  public void execute(JobExecutionContext context) throws JobExecutionException {
    JobKey jobKey = context.getJobDetail().getKey();
    _log.info("SimpleJob says: " + jobKey + " executing at " + new Date());
  }
}

CronTriggerExample.java:

public class CronTriggerExample {
    public void run() throws Exception {
        Logger log = LoggerFactory.getLogger(CronTriggerExample.class);
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        JobDetail job = newJob(SimpleJob.class)
            .withIdentity("job1", "group1")
            .build();
        CronTrigger trigger = newTrigger()
            .withIdentity("trigger1", "group1")
            .withSchedule(cronSchedule("0/3 * * * * ?"))
            .build();

        Date ft = sched.scheduleJob(job, trigger);
        log.info(job.getKey() + " has been scheduled to run at: " + ft
            + " and repeat based on expression: "
            + trigger.getCronExpression());

        sched.start();
    }

    public static void main(String[] args) throws Exception {
        CronTriggerExample example = new CronTriggerExample();
        example.run();
    }
}

上面的代码运行良好,如果我将main方法中的两行代码移动到 junit 测试类(junit4),如下所示:

public class Test1 {
    @Test
    public void run() throws Exception {
        CronTriggerExample example = new CronTriggerExample();
        example.run();
    }
}

作业没有运行。

我很困惑为什么同样的代码不能在 junit 中运行?

要自己查看问题,我建议在 Eclipse 等 IDE 中以调试模式运行这两条不同的代码。

当您在main中运行这两行时,即使main终止,您创建的 Quartz Scheduler 也会继续运行。

当您在 JUnit 中运行这两行代码时,JUnit 框架会在所有单元测试终止时终止所有剩余的线程。

为了让 Quartz 有时间触发您的 Job,您应该使用以下代码更改您的 JUnit 测试

public class Test1 {
    @Test
    public void run() throws Exception {
        CronTriggerExample example = new CronTriggerExample();
        example.run();

        Thread.sleep(240000); // Sleep 4 minutes (4*60*1.000 = 240.000)
    }
 }

您需要在 Quartz 线程运行时阻塞主线程,否则正如@Kraiss 所说,测试几乎会立即终止。 要在你的测试中做任何有用的事情,比如从那些 Quartz 创建的线程中执行断言,你可以使用像ConcurrentUnit这样的东西来提供帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM