0
0
JUnittesting~10 mins

Why exception testing validates error handling in JUnit - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the method throws the expected exception.

JUnit
assertThrows([1].class, () -> calculator.divide(10, 0));
Drag options to blanks, or click blank then click option'
AIllegalArgumentException
BNullPointerException
CIOException
DArithmeticException
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type like NullPointerException.
Not using the exception class with .class suffix.
2fill in blank
medium

Complete the code to verify the exception message contains the expected text.

JUnit
Exception exception = assertThrows(IllegalArgumentException.class, () -> parser.parse(null));
assertTrue(exception.getMessage().[1]("input cannot be null"));
Drag options to blanks, or click blank then click option'
Aequals
Bcontains
CstartsWith
DendsWith
Attempts:
3 left
💡 Hint
Common Mistakes
Using equals which requires exact match.
Using startsWith or endsWith which only check the start or end.
3fill in blank
hard

Fix the error in the test code to properly catch the exception.

JUnit
try {
    service.process(null);
    fail("Expected [1] to be thrown");
} catch (NullPointerException e) {
    // test passes
}
Drag options to blanks, or click blank then click option'
ANullPointerException
BIllegalStateException
CIOException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching exception type in fail message and catch block.
Using a generic exception type that is not thrown.
4fill in blank
hard

Fill both blanks to assert that the method throws the correct exception with the expected message.

JUnit
IllegalArgumentException thrown = assertThrows([1].class, () -> validator.validate(""));
assertEquals("[2]", thrown.getMessage());
Drag options to blanks, or click blank then click option'
AIllegalArgumentException
BNullPointerException
CInput cannot be empty
DValue is null
Attempts:
3 left
💡 Hint
Common Mistakes
Using NullPointerException instead of IllegalArgumentException.
Using wrong exception message text.
5fill in blank
hard

Fill all three blanks to test that the method throws the expected exception type, and the message contains the correct text.

JUnit
Exception exception = assertThrows([1].class, () -> fileReader.readFile(null));
String expectedMessage = "[2]";
assertTrue(exception.getMessage().[3](expectedMessage));
Drag options to blanks, or click blank then click option'
AIllegalArgumentException
BFile path must not be null
Ccontains
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Using IOException instead of IllegalArgumentException.
Checking message with equals instead of contains.