Is it possible to access instance of exception “catched” with JUnit Rule ExpectedException?

Tags: , , , ,



Suppose that in a test is:

@Rule
public ExpectedException thrown = ExpectedException.none();

and some test contains:

thrown.expect(SomeNastyException.class);

Now if there is a need to inspect this SomeNastyException more detailed what would be the way?

Of course it would be possible just not to use ExcpectedException and wrap call with try/catch and then inspect the exception in any way it is needed but now question is about can it be done with ExpectedException, something like:

assertEquals("42", thrown.getException().getUniversalAnswerToEverything());

Answer

There is a less specialized version of expect method in that rule, that accepts a Hamcrest’s matcher:

expect(Matcher)

This method would allow you to assert almost anything about the thrown exception, provided there is a Matcher implementation for that.

For instance, for your case it’d look something like this:

import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;

....

exceptions.expect(hasProperty("UniversalAnswerToEverything", is(42)));

Hamcrest has a pretty flexible matcher model, so you can also easily write your own if you aren’t satisfied with what’s inlucded in the library.



Source: stackoverflow