Mockito
Java
Software Testing
Generic Parameters
Unit Testing

Mockito: mock a generic class or interface

Codemia Knowledge Hub ·

To mock a class or interface with generic parameters in Mockito, call mock() on the raw class and assign the result to the parameterized type, as in mockedList = mock(List.class) with mockedList declared as a list of strings. You stub and verify it the same way as any other mock. Because of Java's type erasure, the type argument only exists at compile time, so keeping it consistent is up to you.

Generics and type erasure

Generics let classes, interfaces and methods work with different types while catching more bugs at compile time. Java's type erasure removes the generic type information during compilation, which is why you pass the raw class (such as List.class) to Mockito. Mockito can mock concrete classes, abstract classes and interfaces, generic or not.

Mocking a generic interface

The steps are the same as for non-generic types:

java
1import static org.mockito.Mockito.*;
2
3import java.util.List;
4
5public class MockGenericExample {
6    public static void main(String[] args) {
7        // Create Mock
8        List<String> mockedList = mock(List.class);
9
10        // Use Mock
11        mockedList.add("one");
12        mockedList.clear();
13
14        // Verify
15        verify(mockedList).add("one");
16        verify(mockedList).clear();
17    }
18}

List is a generic interface, and it is mocked here without a type parameter. Assigning it to a parameterized variable is an unchecked conversion (the compiler may warn about it); at runtime the mock is simply a List.

Stubbing a method with a generic return type

Methods whose return type is a type parameter look trickier. Take this interface:

java
public interface Service<T> {
    T process(T data);
}

Mock and stub it like this:

java
1import static org.mockito.Mockito.*;
2
3public class GenericMethodMock {
4    public static void main(String[] args) {
5        // Mocking a generic interface
6        Service<String> mockService = mock(Service.class);
7
8        // Stubbing the method
9        when(mockService.process("input")).thenReturn("processed");
10
11        // Use and check
12        String result = mockService.process("input");
13        if (!"processed".equals(result)) {
14            throw new AssertionError("expected processed but got " + result);
15        }
16    }
17}

Mockito mocks Service<T> and stubs process(T data) without any special handling. Make sure the generic types on the mock declaration and in the stubbing line up, because the compiler only checks them against the declared type.

The check uses an explicit throw rather than Java's assert, which does nothing unless the JVM runs with -ea. In a real test, use your framework's assertEquals.

Avoiding the unchecked warning

mock(Service.class) compiles with an unchecked conversion warning. Two ways to avoid it:

java
1// Mockito 4.10+: the type is inferred from the variable, no warning
2Service<String> mockService = mock();
3
4// Field injection with JUnit 5 and @ExtendWith(MockitoExtension.class)
5@Mock
6Service<String> mockService;

What Mockito cannot see

Due to type erasure, Mockito cannot tell List<String> from List<Integer> at runtime. Careful design and clear test scope usually work around this.

FeatureConsideration
Generic Interfaces/ClassesCan be mocked directly but watch for type erasure.
Generic MethodsEnsure correct usage of generic types in stubbing.
Type SafetyManaged by the developer through the declared generic types.
Limitations due to Type ErasureMockito cannot differentiate between parameterized types at runtime.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms