J'ai une tâche que j'ai prévu de lancer toutes les 30 minutes. J'ai utilisé ScheduledExecutorService pour planifier.Comment tester la gestion des exceptions ScheduledExecutorService dans Junit?
Je souhaite tester (junit) la gestion des exceptions pour ScheduledExecutorService de sorte que, lorsqu'une exception est levée, le thread ne meurt pas à cause de l'exception.
Mon code:
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;
}
}
Pour le moment, mon chèque de test unitaire pour la fonctionnalité:
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 {
}
};
}
}
Je veux dire que je veux m'assurer qu'il ne tue pas le thread quand il y a une exception d'exécution. – user3407267
J'ai amélioré ma réponse. J'espère que cela pourra aider. – GhostCat