I have written a few JUnit tests with @Test
annotation. If my test method throws a checked exception and if I want to assert the message along with the exception, is there a way to do so with JUnit @Test
annotation? AFAIK, JUnit 4.7 doesn't provide this feature but does any future versions provide it? I know in .NET you can assert the message and the exception class. Looking for similar feature in the Java world.
This is what I want:
@Test (expected = RuntimeException.class, message = "Employee ID is null")
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() {}
Import the catch-exception library, and use that. It's much cleaner than the
ExpectedException
rule or atry-catch
.Example form their docs:
Actually, the best usage is with try/catch. Why? Because you can control the place where you expect the exception.
Consider this example:
What if one day the code is modified and test preparation will throw a RuntimeException? In that case actual test is not even tested and even if it doesn't throw any exception the test will pass.
That is why it is much better to use try/catch than to rely on the annotation.
Do you have to use
@Test(expected=SomeException.class)
? When we have to assert the actual message of the exception, this is what we do.I like user64141's answer but found that it could be more generalized. Here's my take:
Note that leaving the "fail" statement within the try block causes the related assertion exception to be caught; using return within the catch statement prevents this.
In JUnit 4.13 (once released) you can do:
This also works in JUnit 5 but with different imports:
Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.
Add this utility class:
Then for my unit test, all I need is this code: