0
0
JUnittesting~10 mins

assertThrows usage in JUnit - Interactive Code Practice

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

Complete the code to assert that a NullPointerException is thrown.

JUnit
assertThrows([1].class, () -> { throw new NullPointerException(); });
Drag options to blanks, or click blank then click option'
AIllegalArgumentException
BIndexOutOfBoundsException
CArithmeticException
DNullPointerException
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception class.
Not using the .class suffix.
2fill in blank
medium

Complete the code to assert that an ArithmeticException is thrown when dividing by zero.

JUnit
assertThrows([1].class, () -> { int result = 10 / 0; });
Drag options to blanks, or click blank then click option'
ANullPointerException
BNumberFormatException
CArithmeticException
DIllegalStateException
Attempts:
3 left
💡 Hint
Common Mistakes
Using NullPointerException instead of ArithmeticException.
Forgetting to use .class after the exception name.
3fill in blank
hard

Fix the error in the assertThrows usage to correctly check for IndexOutOfBoundsException.

JUnit
assertThrows([1], () -> { List<String> list = List.of(); list.get(1); });
Drag options to blanks, or click blank then click option'
AIndexOutOfBoundsException()
BIndexOutOfBoundsException.class
Cnew IndexOutOfBoundsException()
DIndexOutOfBoundsException
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the exception class name without .class.
Passing a new exception instance instead of the class.
4fill in blank
hard

Fill both blanks to assert that a NumberFormatException is thrown when parsing an invalid number.

JUnit
assertThrows([1].class, () -> { Integer.parseInt([2]); });
Drag options to blanks, or click blank then click option'
ANumberFormatException
B"abc"
C"123"
DIllegalArgumentException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a valid number string like "123" which does not throw.
Using the wrong exception class.
5fill in blank
hard

Fill all three blanks to assert that an IllegalArgumentException is thrown with a specific message.

JUnit
IllegalArgumentException exception = assertThrows([1].class, () -> { throw new IllegalArgumentException([2]); });
assertEquals([3], exception.getMessage());
Drag options to blanks, or click blank then click option'
AIllegalArgumentException
B"Invalid input"
DNullPointerException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different exception class.
Mismatching the exception message string.