Test Overview
This test verifies that a mock using the Answer interface returns dynamic responses based on the input argument. It checks that the method returns the expected string with the input value included.
This test verifies that a mock using the Answer interface returns dynamic responses based on the input argument. It checks that the method returns the expected string with the input value included.
import static org.mockito.Mockito.*; import static org.mockito.ArgumentMatchers.*; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import static org.junit.jupiter.api.Assertions.*; public class DynamicAnswerTest { interface GreetingService { String greet(String name); } @Test public void testDynamicAnswer() { GreetingService mockService = mock(GreetingService.class); Answer<String> dynamicAnswer = invocation -> { String name = invocation.getArgument(0, String.class); return "Hello, " + name + "!"; }; when(mockService.greet(anyString())).thenAnswer(dynamicAnswer); String result = mockService.greet("Alice"); assertEquals("Hello, Alice!", result); result = mockService.greet("Bob"); assertEquals("Hello, Bob!", result); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | — | PASS |
| 2 | Mockito creates mock of GreetingService interface | Mock object ready to intercept greet calls | — | PASS |
| 3 | Define Answer interface implementation to return 'Hello, <name>!' dynamically | Answer object prepared to handle greet method calls | — | PASS |
| 4 | Stub mockService.greet(anyString()) to use the dynamic Answer | Mock configured to respond dynamically based on input | — | PASS |
| 5 | Call mockService.greet("Alice") | Method intercepted by mock, Answer invoked with argument "Alice" | Check returned string equals "Hello, Alice!" | PASS |
| 6 | Call mockService.greet("Bob") | Method intercepted by mock, Answer invoked with argument "Bob" | Check returned string equals "Hello, Bob!" | PASS |
| 7 | Test ends successfully | All assertions passed | — | PASS |
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