mock instance is null after @Mock annotation
Solution 1
When you want to use the @Mock
annotation you should use the MockitoJUnitRunner
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
See also this tutorial.
Solution 2
You have three options for activating the @Mock
annotation: MockitoRule, MockitoJUnitRunner, MockitoAnnotations.initMocks(this). IMHO using the MockitoRule
is the best one, because it lets you still choose another runner like e.g. Parameterized
.
Use the MockitoRule
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Use the MockitoJUnitRunner
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Call MockitoAnnotations.initMocks(this) explicitly.
This can be done in qn @Before
method, in your own runner or in an own rule.
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Before
public void createMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Solution 3
Same problem can occur if you are using Junit5 since there is no more '@RunWith' annotation.
In this case you should annotate your class with:
@ExtendWith(MockitoExtension.class)
public class MyTestClass {
...
You should also import into your dependency (Maven - pom.xml):
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
Solution 4
If you use junit.jupiter
with @ExtendWith(MockitoExtension.class)
for test class but mocks are null, ensure that @Test
annotation is imported from
import org.junit.jupiter.api.Test;
instead of org.junit.Test;
Solution 5
What solved this issue for me (combination of answers above and my own additions):
MockitoAnnotations.initMocks(this);
in the@Before
method- Test class must be public
- Test methods must be public
import org.junit.Test;
instead ofimport org.junit.jupiter.api.Test;
When doing command + N --> Test...
in Intellij it generates (as a default at least) some boilerplate that did not work in my case.
Related videos on Youtube
Elad Benda2
Updated on July 11, 2022Comments
-
Elad Benda2 almost 2 years
I try to run this test:
@Mock IRoutingObjHttpClient routingClientMock; @Mock IRoutingResponseRepository routingResponseRepositoryMock; @Test public void testSendRoutingRequest() throws Exception { CompleteRoutingResponse completeRoutingResponse = new CompleteRoutingResponse(); completeRoutingResponse.regression_latencyMillis = 500L; Mockito.when(routingClientMock.sendRoutingRequest(any(RoutingRequest.class))).thenReturn(completeRoutingResponse); RoutingObjHttpClientWithReRun routingObjHttpClientWithReRun = new RoutingObjHttpClientWithReRun (routingClientMock, routingResponseRepositoryMock); ... }
but I get NullPointerException for:
Mockito.when(routingClientMock.
what am i missing?
-
Andy Turner about 9 yearsDo you call
MockitoAnnotations.initMocks(this)
? (Should probably be in @Before method) Or, do you have any other @Rule which you expect to initialize your mocks? (It isn't automagic) -
Tim Biegeleisen about 9 yearsYou need to instantiate the
routingClientMock
e.g.routingClientMock = Mockito.mock(RoutingObjHtttpClient.class);
-
Roland Weisleder about 9 yearsYou could also use
@RunWith(MockitoJUnitRunner.class)
at your class -
Elad Benda2 about 9 yearsplease write as an answer and I'll mark it
-
-
Elad Benda2 about 9 yearswhy
@RunWith(SpringJUnit4ClassRunner.class)
and notMockitoJUnitRunner.class
? -
Piyush Agarwal over 6 yearsIt doesnt work for me always gives this error "dexcache == null (and no default could be found; consider setting the 'dexmaker.dexcache' system property)"
-
Roland Weisleder over 6 years@pyus13 This should be a new question with more code.
-
Piyush Agarwal over 6 yearsAppreciate the response, I think the problem was I was using it in JUnit Test and while some code merges someone from team mistakenly added dex maker testImplementation dependencies. After removing that line from build.gradle things were started working. Thanks hope this will save someone's time.
-
David almost 6 yearsBy using @Mock annotation this giving a build failed.
-
Roland Weisleder almost 6 years@David I think your problem should be a new question with a complete example.
-
David almost 6 years@RolandWeisleder sure. Let me post a question.
-
David Victor over 4 yearsYou don't need SpringJUnit4ClassRunner unless you want to wire in some Spring context into your test - which is a very twisty passage of its own.
-
Nakul Goyal over 3 yearsIn most of the test classes @RunWith(MockitoJUnitRunner.class) works fine in injecting mocks. But in few test classes both @RunWith(MockitoJUnitRunner.class) and MockitoAnnotations.initMocks(this) worked together only. Is there any explaination for this issue ?
-
Stefan Birkner over 3 yearsCan you please create another question on StackOverflow with a complete example.
-
RainHunter over 3 yearsThis is very likely the right solution for most people reading this thread nowadays.
-
Mohamed Ali over 3 yearsThank you so much you saved me. My issue was the last one you commented on. Much love!
-
Tim Biegeleisen over 3 yearsThis answer literally saved my life, and it should probably be listed near the very top of all answers +1.
-
phi over 3 yearsBest answer in 2021
-
Llama about 3 yearsthat tutorial is trash
-
Rakhi Dhavale almost 3 yearsSaved me a lot of time, thanks ! You're right, after using
@RunWith(MockitoJUnitRunner.class)
, I was not able to mock the objects, the IntelliJ IDE was constantly throwing error that the mocked object is null. Finally all my test cases ran successfully after replacing it with@ExtendWith(MockitoExtension.class)
-
mike over 2 yearsOne of them is enough for use @mock annotation
-
Junio over 2 yearsMy scenario includes
@RunWith(PowerMockRunner.class)
and@PowerMockRunnerDelegate(Parameterized.class)
. For each param declared under@Parameterized.Parameters
the@Before
annotations invokes some mocked objectsnull
. Without parameters, tests run fine, no NPE. With parameteres, neededMockitoAnnotations.initMocks(this)
. Thanks! -
Marcin K. over 2 yearsThis was the fix for me. Thanks mate!
-
Onkar Patil about 2 yearsYou are saver a man, I spent 3 hours until coming here. Thanks lot. +1
-
Christian Vincenzo Traina almost 2 yearsI don't know what's wrong, but it says that
init()
must be static