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:
mock()when()verify()spy()doReturn()doThrow()times()never()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.
Using the Mockito. prefix reduces code readability and makes test files unnecessarily verbose.
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.
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);
}
}
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);
}
}
(visible only on this page)
Use a static import for "{method name}".