3

我需要为此测试InterruptedExceptionExecutionException编写 JUnit。

请就此给我建议。我如何中断线程来复制场景。将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)
        }

    }
}
4

1 回答 1

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();
于 2013-06-18T21:24:50.777 回答