Skip to content
Advertisement

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

Suppose that in a test is:

JavaScript

and some test contains:

JavaScript

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:

JavaScript

Advertisement

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement