我有一项计划每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