This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
Question: JUnit 5: How do I determine if an exception was thrown?
Is there a better way to assert that methods will raise exceptions in JUnit 5?
Currently, I have to use @rule to verify that my tests raise exceptions, but that doesn’t apply when I expect multiple methods to raise exceptions in my tests.
Answer:
You can use assertThrows(), which allows you to test multiple exceptions in the same test. Since the advent of lambda support in Java 8, this is the standard way to test exceptions in JUnit.
+200You can use assertThrows(), which allows you to test multiple exceptions in the same test. With Java8Lambda support, which is the canonical way to test exceptions in JUnit. According to JUnit documentation:import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting(a) {
MyException thrown = assertThrows(
MyException.class,
() -> myObject.doThing(),
"Expected doThing() to throw, but it didn't"
);
assertTrue(thrown.getMessage().contains("Stuff"));
}
Copy the code
Answer 2:
Junit5 now provides a way to assert exceptions
You can test both regular and custom exceptions
General exceptions:
ExpectGeneralException.java
public void validateParameters(Integer param ) {
if (param == null) {
throw new NullPointerException("Null parameters are not allowed"); }}Copy the code
ExpectGeneralExceptionTest.java
@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
final ExpectGeneralException generalEx = new ExpectGeneralException();
NullPointerException exception = assertThrows(NullPointerException.class, () -> {
generalEx.validateParameters(null);
});
assertEquals("Null parameters are not allowed", exception.getMessage());
}
Copy the code
You can find an example of testing CustomException here:
ExpectCustomException.java
public String constructErrorMessage(String... args) throws InvalidParameterCountException {
if(args.length! =3) {
throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
}else {
String message = "";
for(String arg: args) {
message += arg;
}
returnmessage; }}Copy the code
ExpectCustomExceptionTest.java
@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
final ExpectCustomException expectEx = new ExpectCustomException();
InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
expectEx.constructErrorMessage("sample "."error");
});
assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}
Copy the code