我需要测试InterruptedExceptionExecutionException并为它们编写JUnits。

请给我建议。我如何中断线程以复制方案。 populateDataForm将启动新线程并将其添加到 future 列表中。

这是我的示例代码:

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)
        }

    }
}

最佳答案

您可以继承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();

09-10 12:26