Expected Exception Flashcards

1
Q

Why

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

assertThrows()

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Using the thrown exception in a subsequent assertion

A

@Test
void testExpectedException() {

NumberFormatException thrown = Assertions.assertThrows(NumberFormatException.class, () -> {
	Integer.parseInt("One");
}, "NumberFormatException was expected");

Assertions.assertEquals("For input string: \"One\"", thrown.getMessage()); }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

assertThrowsExactly()

A

The assertThrowsExactly() method is similar to assertThrows(), but it verifies that only the exact type of exception specified is thrown, and not any subclass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

assertDoesNotThrow()

A

The assertDoesNotThrow() method verifies that no exception is thrown by the block of code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly