March 20, 2018

Assert nested exceptions in jUnit

When working with CompleteableFuture and frameworks like, it is sometimes useful to test for nested exceptions. This little helper class will help you do just that, test for nested exceptions in jUnit.

This class simply takes in the runnable executing the test and runs it. It then catches any throwable exception and checks the cause against the supplied list of causes. If a cause matches, the test succeeds. It the cause cannot be found a flag is set which then fails the entire test in the end.


It can then be used like this:

Super simple and pretty readable as well.

Credit to digitalbreed.