Sameer Sameer - 1 month ago 22
Java Question

JUnit for future.get() Exception scenario

I need to test

InterruptedException
and
ExecutionException
and write JUnits for the same.

Please advice me on this. How can i interrupt the threads to replicate the scenario. The
populateDataForm
will start new threads and add this to futures list.

Here is my sample code:

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

}
}

Answer

You can inherit from MyTest and overload populateData() method as follows:

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

To test the ExecutionException throw RuntimeException instead of the interrupt as follows:

if (1==1)throw new RuntimeException();