[英]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.