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;
}
}