我有一項計劃每30分鐘運行一次的任務。我使用ScheduledExecutorService進行計劃。如何在Junit中測試ScheduledExecutorService異常處理?
我想測試(junit)ScheduledExecutorService的異常處理,以便當有拋出的異常時,線程不會因爲異常而死亡。
我的代碼:
public enum MonitorTask {
TIMER;
private final AtomicBoolean isPublishing = new AtomicBoolean(false);
private final long period = 18000000
public synchronized boolean initialize() {
return initialize(period, period);
}
/**
* @return true, if call was successful i.e. Timer task was scheduled
*/
boolean initialize(long delay, long period) {
if (isPublishing.get()) {
log.warn("Already monitoring for new feature data");
return false;
}
//execute on daemon thread
ScheduledExecutorService scheduledExecutorService =
Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
);
Runnable runnableTask =() -> {
try {
DataPublisher.INSTANCE.update(DateTime.now());
} catch (Throwable e) {
log.warn("Failed to check for new Data!", e);
}
};
scheduledExecutorService.scheduleAtFixedRate(runnableTask, delay, period, TimeUnit.MILLISECONDS);
isPublishing.set(true);
return true;
}
}
至於現在,我需要的功能,單元測試檢查:
public class MonitorTaskTest {
@Test
public void testInitialize() throws Exception {
AtomicInteger val = new AtomicInteger(0);
DataProvider provider = testProvider(val);
assertEquals(0, val.get());
// this should update val every 10 ms (adds 1 to val)
Assert.assertTrue(MonitorTask.TIMER.initialize(0, 10));
assertEquals(0, val.get());
DataPublisher.INSTANCE.registerForNewData(provider, DateTime.now());
// wait for 3 updates
Thread.sleep(10 * 3);
Assert.assertTrue("Expected val to be >= 3 but is " + val.get(), val.get() >= 3);
}
@Before
public void setUp() {
DataPublisher.INSTANCE.clear();
}
private static DataProvider testProvider(final AtomicInteger ai) {
return new DataProvider() {
private AtomicInteger val = ai;
@Override public boolean update(DateTime dateTime) throws Exception {
val.incrementAndGet();
return true;
}
@Override public boolean exists(DateTime dateTime) {
return true;
}
@Override public void close() throws Exception {
}
};
}
}
當它說「單線程終止」它是否也包含運行時異常?我的意思是我想確保它在運行時異常時不會終止線程。 – user3407267
我增強了我的答案。希望有所幫助。 – GhostCat