ExpectedException in jUnit?
-
20-08-2019 - |
Question
Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?
Solution
junit4:
@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
getFile(null);
}
junit3:
void testShouldThrowException() {
try {
getFile(null);
fail("Expected Exception DocumentException");
} catch(DocumentException e) {}
}
OTHER TIPS
You might also consider taking a look at the ExpectedException class which provides richer exception matching.
https://github.com/junit-team/junit/wiki/Exception-testing
Not only you can match the exception class but also you can apply custom matchers to its message.
If you are using Groovy for your junit tests you can use shouldFail.
Here is an example using junit3 style:
void testShouldThrowException() {
def message = shouldFail(DocumentException) {
documentService.getFile(null)
}
assert message == 'Document could not be saved because it ate the homework.'
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow