0
0
JUnittesting~10 mins

Testing multiple exceptions 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 test that the method throws NullPointerException.

JUnit
assertThrows([1].class, () -> myObject.myMethod(null));
Drag options to blanks, or click blank then click option'
ANullPointerException
BIllegalArgumentException
CIOException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception class like IllegalArgumentException.
Not specifying the exception class at all.
2fill in blank
medium

Complete the code to test that the method throws either IOException or SQLException.

JUnit
assertThrows([1].class, () -> myObject.myMethod());
Drag options to blanks, or click blank then click option'
AException
BIOException
CSQLException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Testing only one exception when multiple can be thrown.
Using RuntimeException which does not cover checked exceptions.
3fill in blank
hard

Fix the error in the test that expects multiple exceptions using assertThrows.

JUnit
assertThrows([1].class, () -> myObject.myMethod());
Drag options to blanks, or click blank then click option'
AIOException | SQLException
BException
CSQLException
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use 'IOException | SQLException.class' which is invalid syntax.
Using only one exception class when multiple exceptions can be thrown.
4fill in blank
hard

Fill both blanks to correctly test that either IllegalArgumentException or NullPointerException is thrown.

JUnit
Throwable thrown = assertThrows([1].class, () -> myObject.myMethod([2]));
Drag options to blanks, or click blank then click option'
ARuntimeException
Bnull
C"invalid"
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using Exception.class which is too broad.
Passing a string instead of null to trigger the exception.
5fill in blank
hard

Fill all three blanks to test multiple exceptions and check the exception message.

JUnit
Exception exception = assertThrows([1].class, () -> myObject.myMethod([2]));
assertTrue(exception.getMessage().[3]("error"));
Drag options to blanks, or click blank then click option'
AException
Bnull
Ccontains
DstartsWith
Attempts:
3 left
💡 Hint
Common Mistakes
Using startsWith() which is more restrictive.
Passing a non-null argument that does not cause exception.