mock instance is null after @Mock annotation

111,029

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 of import 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.

Share:
111,029

Related videos on Youtube

Elad Benda2
Author by

Elad Benda2

Updated on July 11, 2022

Comments

  • Elad Benda2
    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
      Andy Turner about 9 years
      Do 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
      Tim Biegeleisen about 9 years
      You need to instantiate the routingClientMock e.g. routingClientMock = Mockito.mock(RoutingObjHtttpClient.class);
    • Roland Weisleder
      Roland Weisleder about 9 years
      You could also use @RunWith(MockitoJUnitRunner.class) at your class
    • Elad Benda2
      Elad Benda2 about 9 years
      please write as an answer and I'll mark it
  • Elad Benda2
    Elad Benda2 about 9 years
    why @RunWith(SpringJUnit4ClassRunner.class) and not MockitoJUnitRunner.class ?
  • Piyush Agarwal
    Piyush Agarwal over 6 years
    It 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
    Roland Weisleder over 6 years
    @pyus13 This should be a new question with more code.
  • Piyush Agarwal
    Piyush Agarwal over 6 years
    Appreciate 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
    David almost 6 years
    By using @Mock annotation this giving a build failed.
  • Roland Weisleder
    Roland Weisleder almost 6 years
    @David I think your problem should be a new question with a complete example.
  • David
    David almost 6 years
    @RolandWeisleder sure. Let me post a question.
  • David Victor
    David Victor over 4 years
    You 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
    Nakul Goyal over 3 years
    In 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
    Stefan Birkner over 3 years
    Can you please create another question on StackOverflow with a complete example.
  • RainHunter
    RainHunter over 3 years
    This is very likely the right solution for most people reading this thread nowadays.
  • Mohamed Ali
    Mohamed Ali over 3 years
    Thank you so much you saved me. My issue was the last one you commented on. Much love!
  • Tim Biegeleisen
    Tim Biegeleisen over 3 years
    This answer literally saved my life, and it should probably be listed near the very top of all answers +1.
  • phi
    phi over 3 years
    Best answer in 2021
  • Llama
    Llama about 3 years
    that tutorial is trash
  • Rakhi Dhavale
    Rakhi Dhavale almost 3 years
    Saved 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
    mike over 2 years
    One of them is enough for use @mock annotation
  • Junio
    Junio over 2 years
    My scenario includes @RunWith(PowerMockRunner.class) and @PowerMockRunnerDelegate(Parameterized.class). For each param declared under @Parameterized.Parameters the @Before annotations invokes some mocked objects null. Without parameters, tests run fine, no NPE. With parameteres, needed MockitoAnnotations.initMocks(this). Thanks!
  • Marcin K.
    Marcin K. over 2 years
    This was the fix for me. Thanks mate!
  • Onkar Patil
    Onkar Patil about 2 years
    You are saver a man, I spent 3 hours until coming here. Thanks lot. +1
  • Christian Vincenzo Traina
    Christian Vincenzo Traina almost 2 years
    I don't know what's wrong, but it says that init() must be static