Automate dynamic response verification using Answer interface in JUnit
Preconditions (3)
✅ Expected Result: The test should pass confirming the service method returns correct dynamic responses as mocked
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doAnswer; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; public class DynamicResponseTest { interface Service { String getResponse(String input); } @Test void testDynamicResponseUsingAnswer() { Service mockService = mock(Service.class); // Use Answer to return dynamic response based on input Answer<String> dynamicAnswer = invocation -> { String arg = invocation.getArgument(0); return "Response for " + arg; }; when(mockService.getResponse(anyString())).thenAnswer(dynamicAnswer); String input = "testInput"; String expected = "Response for testInput"; String actual = mockService.getResponse(input); assertEquals(expected, actual, "The dynamic response should match the expected output"); } }
This test uses Mockito to create a mock of a Service interface.
The Answer interface is implemented with a lambda that returns a dynamic string based on the input argument.
We then stub the getResponse method to use this dynamic answer.
When calling getResponse with "testInput", it returns "Response for testInput".
The assertion verifies the returned value matches the expected dynamic response.
This approach helps test methods that return different outputs based on inputs without hardcoding multiple stubs.
Now add data-driven testing with 3 different inputs to verify dynamic responses
Answer interface in JUnit mocking frameworks like Mockito?Answer interface in Mockito for a method that returns the length of a String argument?when(mock.calculate(anyInt())).thenAnswer(invocation -> {
int x = (int) invocation.getArgument(0);
return x * 2;
});
System.out.println(mock.calculate(5));when(mock.concat(anyString(), anyString())).thenAnswer(invocation -> {
String a = invocation.getArgument(0);
String b = invocation.getArgument(1);
return a + b;
});process(int a, int b) so that it returns the sum of the two arguments only if both are positive; otherwise, it returns zero. Which is the best way to implement this using the Answer interface in Mockito?Pass the test and this pattern moves unknown