0
0
JUnittesting~5 mins

Answer interface for dynamic responses in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe InvocationOnMock object representing the method call
BThe method's return value
CThe mock object itself
DThe test class instance
When should you prefer using Answer interface over thenReturn() in Mockito?
AWhen the return value is always constant
BWhen you want to throw an exception
CWhen you want to verify method calls
DWhen the return value depends on method arguments
Which of the following is a valid way to get the first argument inside answer() method?
Ainvocation.getMethodName()
Binvocation.getReturnValue()
Cinvocation.getArgument(0)
Dinvocation.getMock()
What type of object is typically returned by the answer() method?
Avoid
BAny object matching the mocked method's return type
COnly String objects
DOnly primitive types
Which Mockito method is used to apply an Answer to a mocked method?
Awhen().thenAnswer()
Bverify()
Cwhen().thenReturn()
Dmock()
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.