Objects annotated with Mockito annotations ``++@Mock++``, ``++@Spy++``, ``++@Captor++``, or ``++@InjectMocks++`` need to be initialized explicitly.


There are several ways to do this:

* Call ``++MockitoAnnotations.openMocks(this)++`` or ``++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();++``

Test using uninitialized mocks will fail.


Note that this only applies to annotated Mockito objects. It is not necessary to initialize objects instantiated via ``++Mockito.mock()++`` or ``++Mockito.spy()++``.


This rule raises an issue when a test class uses uninitialized mocks.


== Noncompliant Code Example

----
public class FooTest { // Noncompliant: Mockito initialization missing
  @Mock private Bar bar;       

  @Spy private Baz baz;          

  @InjectMocks private Foo fooUnderTest; 

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

  @Nested
  public class Nested {
    @Mock
    private Bar bar;
  }
----


== Compliant Solution

----
@RunWith(MockitoJUnitRunner.class) 
public class FooTest {
  @Mock private Bar bar;           
  // ...
}
----

----
@ExtendWith(MockitoExtension.class)
public class FooTest {
  @Mock private Bar bar;           
  // ...
}
----

----
public class FooTest {
  @Rule
  public MockitoRule rule = MockitoJUnit.rule(); 

  @Mock private Bar bar;           
  // ...
}
----

----
public class FooTest {
  @Mock private Bar bar;           
  // ...

  @BeforeEach
  void setUp() {
    MockitoAnnotations.openMocks(this);
  }
  // ...
}
----

----
public class FooTest {
  @Mock private Bar bar;           
  // ...

  @Before
  void setUp() {
    MockitoAnnotations.initMocks(this);
  }
  // ...
}
----

----
@ExtendWith(MockitoExtension.class)
public class FooTest {
  @Nested
  public class Nested {
    @Mock
    private Bar bar;
  }
}
----


== See

* https://site.mockito.org/javadoc/current/org/mockito/MockitoAnnotations.html[Mockito documentation - MockitoAnnotations]
* https://site.mockito.org/javadoc/current/org/mockito/junit/MockitoRule.html[Mockito documentation - MockitoRule ]


ifdef::rspecator-view[]
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::rspecator-view[]
