Learnitweb

Using Generic Parameters with Argument Matchers in Mockito

Mockito provides powerful tools to stub method calls with specific or generic parameters. In this tutorial, we’ll focus on using generic parameters with argument matchers like anyInt() in unit tests. This helps simulate behavior when the method can be called with any value of a given type.

1. Objective

To learn how to use argument matchers in Mockito to define mock behavior when methods are called with any type of parameter (like any int, any String, etc).

2. Problem Statement

Suppose we have a mocked List and we want to return a fixed value (e.g., "hello") regardless of which integer index is passed to the get() method.

3. Step-by-Step Example

3.1 Mocking the List and Using anyInt()

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyInt;

import java.util.List;
import org.junit.Test;

public class GenericParameterTest {

    @Test
    public void testListGetWithAnyInt() {
        List<String> mockList = mock(List.class);

        when(mockList.get(anyInt())).thenReturn("hello");

        assertEquals("hello", mockList.get(0));
        assertEquals("hello", mockList.get(1));
        assertEquals("hello", mockList.get(999));
    }
}

Explanation:

  • We use anyInt() from ArgumentMatchers to match any int parameter.
  • The mock returns the same value ("in28Minutes") regardless of the index provided.

3.2 Why Tests Might Fail Unexpectedly

If you’ve already stubbed a method like get(0) to return a specific value and then add anyInt() later, keep in mind:

  • Mockito uses the latest matcher-based stubbing that matches the method call.
  • So get(0) might start returning "in28Minutes" if that matcher is more generic and applied afterward.

3.3 Exploring Other Matchers

Mockito offers a rich set of matchers for various types:

MatcherMatches any…
anyInt()int
anyString()String
anyBoolean()boolean
anyDouble()double
anyList()List of any type
any()Any object of a class

Example Using anyString()

@Test
public void testContainsWithAnyString() {
    List<String> mockList = mock(List.class);

    when(mockList.contains(anyString())).thenReturn(true);

    assertTrue(mockList.contains("foo"));
    assertTrue(mockList.contains("bar"));
}

4. What Are Argument Matchers?

Argument matchers like anyInt() or anyString() are tools provided by Mockito to define stub behavior for flexible inputs. They’re especially useful when:

  • You don’t care about the exact argument value.
  • You want to avoid writing repetitive stubs for multiple inputs.