Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?
ExpectedException in jUnit?
Asked Answered
junit4:
@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
getFile(null);
}
junit3:
void testShouldThrowException() {
try {
getFile(null);
fail("Expected Exception DocumentException");
} catch(DocumentException e) {}
}
I have updated this answer to include a way to do this in jUnit3 –
Lansquenet
The good thing about the "JUnit3" approach is that you can then write one exception-test-case per line, whereas you need five lines for each with the "JUnit4" approach. See my answer for more information: https://mcmap.net/q/1256370/-expectedexception-in-junit –
Sherysherye
Actually the answer using
ExpectedException
by @Maciej is better: https://mcmap.net/q/1256370/-expectedexception-in-junit –
Karr 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.
junit4:
@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
getFile(null);
}
junit3:
void testShouldThrowException() {
try {
getFile(null);
fail("Expected Exception DocumentException");
} catch(DocumentException e) {}
}
I have updated this answer to include a way to do this in jUnit3 –
Lansquenet
The good thing about the "JUnit3" approach is that you can then write one exception-test-case per line, whereas you need five lines for each with the "JUnit4" approach. See my answer for more information: https://mcmap.net/q/1256370/-expectedexception-in-junit –
Sherysherye
Actually the answer using
ExpectedException
by @Maciej is better: https://mcmap.net/q/1256370/-expectedexception-in-junit –
Karr 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.'
}
© 2022 - 2024 — McMap. All rights reserved.