If you’re not familiar with JUnit’s @Rule feature for asserting exceptions in your tests, then read on - you’re about to start using it.
Assert Exception Type
It’s very simple to assert that a given type of exception is thrown in a JUnit test case with the following:
Assert Exception Message (The Old Way)
But, what if you want to be more specific, and check the message itself? I’ve always done the following:
Heres’s another variant you’re probably familiar with:
Assert Exception Message With JUnit Rules
The above methods always felt like hacks. I recently came across JUnit’s @Rule feature, which saves tons of code and is much easier to read. You first define your public ExpectedException instance, and give it a @Rule annotation. Then, in each test case that wants to use it, you set what type of exception you’re expecting, and optionally a substring to look for in the exception message:
Since expectMessage is looking for substrings, you can use several of them to test more complicated exception messages:
More Advanced: Custom Matchers
In my next post, I’ll i describe how to implement a custom Matcher for more complicated Exception assertions.