0
0
JUnittesting~10 mins

when().thenThrow() for 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 mock a method to throw an exception using when().thenThrow().

JUnit
when(mockedList.[1](0)).thenThrow(new IndexOutOfBoundsException());
Drag options to blanks, or click blank then click option'
Aremove
Bget
Cadd
Dclear
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods like add or clear which do not take an index parameter.
Trying to mock a method that does not throw IndexOutOfBoundsException.
2fill in blank
medium

Complete the code to mock a service method to throw a custom exception.

JUnit
when(userService.[1](anyString())).thenThrow(new UserNotFoundException());
Drag options to blanks, or click blank then click option'
AfindUserById
BdeleteUser
CupdateUser
DcreateUser
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing methods that create or update users which usually do not throw not found exceptions.
Using methods that do not accept a string parameter.
3fill in blank
hard

Fix the error in the code to correctly mock throwing an exception with when().thenThrow().

JUnit
when(mockedMap.get([1])).thenThrow(new NullPointerException());
Drag options to blanks, or click blank then click option'
A"key"
Bkey
Cnull
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an unquoted string which causes compilation errors.
Passing null which is valid but not the intended key here.
4fill in blank
hard

Fill both blanks to mock a method that throws an IllegalArgumentException when called with a negative number.

JUnit
when(calculator.[1]([2])).thenThrow(new IllegalArgumentException());
Drag options to blanks, or click blank then click option'
Adivide
B-5
Cadd
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Using the add method which usually does not throw exceptions for negative inputs.
Passing positive numbers instead of negative.
5fill in blank
hard

Fill all three blanks to mock a repository method that throws SQLException when saving a null entity.

JUnit
when(repository.[1]([2])).thenThrow(new [3]());
Drag options to blanks, or click blank then click option'
Asave
Bnull
CSQLException
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using delete instead of save which may not throw SQLException here.
Passing a non-null argument instead of null.