Expected Exception Flashcards
Why
When writing unit tests, it make sense to check whether certain methods throw the expected exceptions when we supply invalid inputs or pre-conditions to not satisfy.
assertThrows()
The assertThrows() method verifies that a particular type of exception (or any of its subclasses) is thrown when a code block is executed.
The assertThrows() will FAIL:
If no exception is thrown from the executable block
If an exception of a different type is thrown
@Test
void testExpectedExceptionFail() {
NumberFormatException thrown = Assertions.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt(“1”);
}, “NumberFormatException error was expected”);
}
For example, in below example “1” is a valid number so no exception will be thrown. This test will fail with the message in the console.
Using the thrown exception in a subsequent assertion
@Test
void testExpectedException() {
NumberFormatException thrown = Assertions.assertThrows(NumberFormatException.class, () -> { Integer.parseInt("One"); }, "NumberFormatException was expected"); Assertions.assertEquals("For input string: \"One\"", thrown.getMessage()); }
assertThrowsExactly()
The assertThrowsExactly() method is similar to assertThrows(), but it verifies that only the exact type of exception specified is thrown, and not any subclass
assertDoesNotThrow()
The assertDoesNotThrow() method verifies that no exception is thrown by the block of code.