Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to mock a method to return a value using doReturn.
JUnit
doReturn("mockedValue").when(mockedObject).[1]();
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not exist in the mocked object.
Confusing doReturn with doThrow.
✗ Incorrect
The method someMethod() is the one being mocked to return "mockedValue" using doReturn.
2fill in blank
mediumComplete the code to mock a method to throw an exception using doThrow.
JUnit
doThrow(new RuntimeException()).when(mockedObject).[1](); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using doReturn instead of doThrow for exceptions.
Mocking a method that does not throw exceptions.
✗ Incorrect
The method throwException() is mocked to throw a RuntimeException using doThrow.
3fill in blank
hardFix the error in the code to correctly mock a method to return a value using doReturn.
JUnit
doReturn("value").when([1]).someMethod();
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the method name inside when() instead of the mocked object.
Using exception classes instead of objects.
✗ Incorrect
The when() method requires the mocked object, not a method or class name.
4fill in blank
hardFill both blanks to mock a method to throw an IllegalArgumentException.
JUnit
doThrow(new [1]()).when([2]).invalidMethod();
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception class.
Confusing the mocked object variable name.
✗ Incorrect
The exception type is IllegalArgumentException and the mocked object is mockedObject.
5fill in blank
hardFill all three blanks to mock a method to return "success" and verify it was called once.
JUnit
doReturn("[1]").when([2]).process(); verify([3], times(1)).process();
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for when() and verify().
Forgetting to match the return value string.
✗ Incorrect
The method returns "success", and the mocked object is mockService used in both when() and verify().