0
0
JUnittesting~10 mins

Answer interface for dynamic responses in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit with Mockito
JUnit
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);
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Mockito creates mock of GreetingService interfaceMock object ready to intercept greet calls-PASS
3Define Answer interface implementation to return 'Hello, <name>!' dynamicallyAnswer object prepared to handle greet method calls-PASS
4Stub mockService.greet(anyString()) to use the dynamic AnswerMock configured to respond dynamically based on input-PASS
5Call mockService.greet("Alice")Method intercepted by mock, Answer invoked with argument "Alice"Check returned string equals "Hello, Alice!"PASS
6Call mockService.greet("Bob")Method intercepted by mock, Answer invoked with argument "Bob"Check returned string equals "Hello, Bob!"PASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The Answer implementation returns incorrect string or does not use the input argument properly
Execution Trace Quiz - 3 Questions
Test your understanding
What does the Answer interface provide in this test?
AA fixed return value for all method calls
BA way to return dynamic responses based on method input
CA way to throw exceptions on method calls
DA method to verify if a method was called
Key Result
Using the Answer interface allows mocks to return different results dynamically based on input arguments, making tests more flexible and realistic.