0
0
JUnittesting~7 mins

Answer interface for dynamic responses in JUnit

Choose your learning style9 modes available
Introduction

We use an Answer interface to create flexible responses in tests. It helps simulate different behaviors dynamically.

When you want a mock to return different values each time it is called.
When the return value depends on the input parameters of the method.
When you want to simulate complex behavior in a mock without writing many separate stubs.
When testing code that calls external services and you want to control responses dynamically.
Syntax
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.

Examples
This example returns a greeting using the first argument passed to the mocked method.
JUnit
Answer<String> answer = invocation -> "Hello " + invocation.getArgument(0);
This example sums two integer arguments passed to the mocked method.
JUnit
Answer<Integer> answer = invocation -> {
    int a = invocation.getArgument(0);
    int b = invocation.getArgument(1);
    return a + b;
};
Sample Program

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.

JUnit
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));
    }
}
OutputSuccess
Important Notes

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.

Summary

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.