我需要测试InterruptedException
和ExecutionException
并为此编写JUnits。
请就此向我提出建议。我如何中断线程来复制场景。 populateDataForm
将启动新主题并将其添加到期货列表中。
以下是我的示例代码:
class MyTest{
public populateData(){
Collection<Future<?>> futures = new LinkedList<Future<?>>();
DataSet ds = Helper.populateDataForm(employee, futures);
waitForTaskCompletion(futures);
}
private waitForTaskCompletion(futures){
for (Future<?> future:futures) {
try {
future.get();
} catch (InterruptedException e) {
throw new CustomExcpetion("Message1", e)
} catch (ExecutionException e) {
throw new CustomExcpetion("Message2", e)
}
}
}
答案 0 :(得分:1)
您可以继承MyTest
并重载populateData()
方法,如下所示:
public void populateData() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> calls = new Callable<String>() {
@Override
public String call() throws Exception {
for (;;){
Thread.sleep(100);
// You call interrupt here, which causes Future.get() interrupt
Thread.currentThread().interrupt();
if (1 > 2) break;
}
return null;
}
};
final Future<String> future = executorService.submit(calls);
waitForTaskCompletion(future);
executorService.shutdown();
}
要测试ExecutionException
抛出RuntimeException
而不是中断,如下所示:
if (1==1)throw new RuntimeException();