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 |