We use an Answer interface to create flexible responses in tests. It helps simulate different behaviors dynamically.
Answer interface for dynamic responses in JUnit
Answer<Type> answer = invocation -> {
// your dynamic response logic here
return value;
};The Answer interface is a functional interface with one method: Object answer(InvocationOnMock invocation).
You implement the answer method to define what the mock should return when called.
Answer<String> answer = invocation -> "Hello " + invocation.getArgument(0);
Answer<Integer> answer = invocation -> {
int a = invocation.getArgument(0);
int b = invocation.getArgument(1);
return a + b;
};This test mocks a Calculator interface. The add method returns the sum of its two arguments dynamically using the Answer interface. The assertions check that the mock returns correct sums for different inputs.
import static org.mockito.Mockito.*; import org.mockito.stubbing.Answer; import org.mockito.invocation.InvocationOnMock; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; interface Calculator { int add(int a, int b); } public class AnswerInterfaceTest { @Test void testDynamicAdd() { Calculator calc = mock(Calculator.class); Answer<Integer> addAnswer = invocation -> { int a = invocation.getArgument(0); int b = invocation.getArgument(1); return a + b; }; when(calc.add(anyInt(), anyInt())).thenAnswer(addAnswer); assertEquals(5, calc.add(2, 3)); assertEquals(0, calc.add(-1, 1)); assertEquals(10, calc.add(7, 3)); } }
Use invocation.getArgument(index) to access method parameters inside the Answer.
Answer interface helps avoid writing many separate stubs for different inputs.
Remember to import Mockito and JUnit 5 libraries to run the example.
The Answer interface lets you create dynamic mock responses based on input.
It is useful for simulating complex or variable behavior in tests.
Using Answer improves test flexibility and reduces repetitive code.