Recall & Review
beginner
What is the purpose of the Answer interface in JUnit testing?
The Answer interface allows you to define dynamic responses for mocked methods, enabling custom behavior when a method is called during a test.
Click to reveal answer
intermediate
How do you implement the Answer interface to return a value based on method arguments?
Implement the Answer interface's answer(InvocationOnMock invocation) method, extract arguments from invocation.getArguments(), and return a value computed from those arguments.
Click to reveal answer
beginner
Which method must be overridden when using the Answer interface?
You must override the answer(InvocationOnMock invocation) method to define the behavior of the mocked method call.
Click to reveal answer
intermediate
Why use Answer interface instead of simple when().thenReturn() in Mockito?
Answer interface is used when the return value depends on the input arguments or when you want to execute custom logic on method calls, which thenReturn() cannot handle.
Click to reveal answer
intermediate
Show a simple example of using Answer interface to return the sum of two integer arguments.
Example:
Answer<Integer> sumAnswer = invocation -> {
int a = (int) invocation.getArgument(0);
int b = (int) invocation.getArgument(1);
return a + b;
};
when(mockedObject.add(anyInt(), anyInt())).thenAnswer(sumAnswer);
Click to reveal answer
What does the Answer interface's answer() method receive as a parameter?
✗ Incorrect
The answer() method receives an InvocationOnMock object, which provides details about the method call, including arguments.
When should you prefer using Answer interface over thenReturn() in Mockito?
✗ Incorrect
Answer interface is useful when the return value depends on the input arguments, allowing dynamic responses.
Which of the following is a valid way to get the first argument inside answer() method?
✗ Incorrect
invocation.getArgument(0) returns the first argument passed to the mocked method.
What type of object is typically returned by the answer() method?
✗ Incorrect
The answer() method must return an object compatible with the mocked method's return type.
Which Mockito method is used to apply an Answer to a mocked method?
✗ Incorrect
Use when().thenAnswer() to specify a dynamic response using the Answer interface.
Explain how the Answer interface helps create dynamic responses in Mockito tests.
Think about how you can customize what a mock returns based on input.
You got /4 concepts.
Describe a scenario where using Answer interface is better than thenReturn() for mocking.
Consider when the output changes with different inputs.
You got /3 concepts.