Initialize Mockito objects

Annotated Mockito objects (@Mock, @Spy, @Captor, @InjectMocks) need to be initialized explicitly.

There are several ways to do this:

  • Call MockitoAnnotations.initMocks(this) in a setup method
  • Annotate test class with @RunWith(MockitoJUnitRunner.class) (JUnit 4)
  • Annotate test class with @ExtendWith(MockitoExtension.class) (JUnit 5 Jupiter)
  • Use @Rule public MockitoRule rule = MockitoJUnit.rule();

Leaving the objects uninitialized is a bug.

Snippet of Noncompliant Code

public class FooTest { // Non-Compliant: Mockito initialization missing
  @Mock private Bar bar;       
     
  @Spy private Baz baz;          

  @InjectMocks private Foo fooUnderTest; 

  @Test
  void someTest() {
    // test something ...
  }
}

Snippet of Compliant Code

@RunWith(MockitoJUnitRunner.class) 
public class FooTest { // Compliant -- runs with MockitoJUnitRunner
  @Mock private Bar bar;           
  // ...
}
@ExtendWith(MockitoExtension.class)
public class FooTest { // Compliant -- runs with MockitoExtension
  @Mock private Bar bar;           
  // ...
}
public class FooTest { // Compliant -- uses MockitoRule
  @Rule
  public MockitoRule rule = MockitoJUnit.rule(); 

  @Mock private Bar bar;           
  // ...
}
public class FooTest { // Compliant -- calls initMocks
  @Mock private Bar bar;           
  // ...

  @BeforeEach
  void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  // ...
}

Exceptions

This only applies to annotated Mockito objects. It is not necessary to initialize objects instantiated via Mockito.mock() or Mockito.spy().

External references and/or language specifications

Hi @bduderstadt,

Thank you for this detailed rule, it is greatly appreciated.

This is indeed a bug, and we can implement this rule.

Just to manage expectation, we will not implement this rule right away. For now we focus on cases where tests pass despite a bug being present or when tests are badly designed. This is where SonarQube/SonarCloud/SonarLint can provide most of their value.

The bug described by this rule would make every test using mocks fail, which means that the information provided by SonarQube/SonarCloud would be redundant. It could be useful in SonarLint to help developers find the issue faster. Don’t hesitate to correct me if you see a case were tests would pass and mocks have not been initialized.

I’ll create the rule description so that we can implement it later.

Cheers,

1 Like

FYI the rule description is available here: https://jira.sonarsource.com/browse/RSPEC-5979.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.