This rule raises an issue when Mockito core methods are called with the Mockito. prefix instead of being statically imported.

This applies to the following Mockito methods:

Why is this an issue?

Mockito was designed with static imports in mind to create a more readable, fluent testing DSL (Domain-Specific Language). When you use the Mockito. prefix for method calls, the test code becomes more verbose and harder to read.

Compare these two examples:

var myMock = Mockito.mock(MyService.class);
Mockito.when(myMock.getValue()).thenReturn(42);

versus:

var myMock = mock(MyService.class);
when(myMock.getValue()).thenReturn(42);

The second version reads more naturally, almost like plain English, which is the intent of Mockito’s API design. This readability improvement becomes even more significant in larger test files with many mock interactions.

What is the potential impact?

Using the Mockito. prefix reduces code readability and makes test files unnecessarily verbose.

How to fix it

Add a static import for Mockito methods at the top of your test class and remove the Mockito. prefix from method calls. You can import specific methods or use a wildcard import for commonly used Mockito methods.

Code examples

Noncompliant code example

import org.mockito.Mockito;

public class MyServiceTest {
    private MyService myService = Mockito.mock(MyService.class);

    @Test
    public void testBehavior() {
        Mockito.when(myService.getValue()).thenReturn(42); // Noncompliant

        int result = myService.getValue();

        Mockito.verify(myService).getValue(); // Noncompliant
        assertEquals(42, result);
    }
}

Compliant solution

import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;

public class MyServiceTest {
    private MyService myService = mock(MyService.class);

    @Test
    public void testBehavior() {
        when(myService.getValue()).thenReturn(42);

        int result = myService.getValue();

        verify(myService).getValue();
        assertEquals(42, result);
    }
}

Resources

Documentation


Implementation Specification

(visible only on this page)

Message

Use a static import for "{method name}".

Highlighting