In Java, we can test exceptions via unit tests in a few different ways. In this article, I’ll present common methods of doing that. Nevertheless, I suppose we there are different methods as well.

First method is basically wrapping a method call with try-catch block, assigning an exception to a variable and performing appropriate assertion. In these examples, I’m using JUnit for unit tests and Truth for assertions.

In the second method, we can define a type of the thrown exception within the @Test annotation. It’s useful approach when we don’t want to test exception details like message and we care only about the type.

We can also test exceptions with AssertJ library as follows:

Another method allows us to test exception type, message and other details without wrapping method call with try-catch block, what increases code readibility and makes it clear. In order to achieve that, we need @Rule annotation and ExpectedException object like in the code snippet below. What is important in this example, we have to define assertions in the beginning and invoke method, which will throw an exception after these assertions. It’s different order than in a regular unit test.

Alternatively, we can experiment with Vavr and Try interface.

We can even go crazy and prepare RxJava wrapper for our exception.

and write test like that:

For sure, it shouldn’t be default choice and I wrote it just for a little experiment. Don’t treat that as a production-ready code (unless there’s a reson you really need something like that).

I think, we can find even more ways of testing exceptions. In my opinion, solution with JUnit and @Rule annotation is the cleanest and most flexible one among all of the approaches presented here. It’s good to mention that last two approaches are just experiments. I also recommend Truth for writing assertions. Nevertheless, libraries like FEST, AssertJ and others, which have fluent interfaces helping in error analysis are also worth considering in daily usage.

Do you know other (maybe better) approaches of testing exceptions in Java? Share them in comments :-).