JUnit for future.get()异常场景

时间:2013-06-18 18:00:51

标签: java multithreading junit4

我需要测试InterruptedExceptionExecutionException并为此编写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)
        }

    }
}

1 个答案:

答案 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();