mock instance is null after @Mock annotation

JavaUnit TestingJunitMockingMockito

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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 - Java

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.

Solution 6 - Java

For me, even after adding @RunWith(MockitoJUnitRunner.class) it was not working.
Turned out, I had made the silly mistake of importing @Test from

import org.junit.jupiter.api.Test;

instead of

import org.junit.Test;

After correcting it, it worked!

Solution 7 - Java

It can also be an import problem, so make sure you have the appropriate imported package.

For example, the "org.easymock" package also does have an annotation called @Mock, which of course, won't work with Mockito specific setup.

Solution 8 - Java

  1. You should use @RunWith(SpringJUnit4ClassRunner.class) at your class
  2. You have to call MockitoAnnotations.initMocks(this); in @Before method

Solution 9 - Java

I had the problem that I declared @Mock MyClass myClass and then tried to mock a behaviour inside my @BeforeAll annotated method:

@Mock
private MyClass myClass;

...

@BeforeAll
public void init()
{
    ...
    Mockito.when(myClass.something()).thenReturn("Not found")
    ...
}

Apparently init() was executed before the mock initialization of myClass, so myClass == null inside init().

The solution was to change the annotation from @BeforeAll to @BeforeEach.

Solution 10 - Java

Try to to check if the method that you are calling is a final method or not.

Mockito cannot mock the final method. https://github.com/mockito/mockito/wiki/FAQ

Solution 11 - Java

For me it worked when I added :

  1. At class level:
@RunWith(MockitoJUnitRunner.class).
  1. Inside class:
@Before
      public void createMocks() {
        MockitoAnnotations.initMocks(this);
      }

Solution 12 - Java

Add @ExtendWith(MockitoExtension.class) annotation to the test class and it should work given You are using Junit 5+ version. If you are using older version of Junit use @RunWith(MockitoJUnitRunner.class) annotation.

Solution 13 - Java

For me adding the annotation to the class:

@RunWith(MockitoJUnitRunner.class)

and modifying the version of Mockito solved this issue.

<dependency>
		<groupId>org.mockito</groupId>
		<artifactId>mockito-core</artifactId>
		<version>2.23.4</version>
		<scope>test</scope>
</dependency>

Solution 14 - Java

I had the same issue, but I found updating my tests (which were originally written for JUnit 3 and used the legacy setUp() and tearDown() methods) to JUnit 4 and modern annotated fixture methods worked.

Additionally, if you're using the Rule:

@Rule public MockitoRule rule = MockitoJUnit.rule();

Make sure the rule is also on a public class or you will receive the message:

How did getFields return a field we couldn't access?

Solution 15 - Java

Found this solution in comments that worked for me. Do this for all the mocks you are creating.

You need to instantiate the routingClientMock e.g.

routingClientMock = Mockito.mock(RoutingObjHtttpClient.class);

Solution 16 - Java

If you are also using PowerMock then

@RunWith(MockitoJUnitRunner.class)

can be replaced with

@RunWith(PowerMockRunner.class)

This will activate your @Mocks and enable the PowerMock functionality.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElad Benda2View Question on Stackoverflow
Solution 1 - JavaRoland WeislederView Answer on Stackoverflow
Solution 2 - JavaStefan BirknerView Answer on Stackoverflow
Solution 3 - JavaGjeraView Answer on Stackoverflow
Solution 4 - JavaRammgarotView Answer on Stackoverflow
Solution 5 - JavaamanateeView Answer on Stackoverflow
Solution 6 - JavaGanesh SatputeView Answer on Stackoverflow
Solution 7 - JavaZ3d4sView Answer on Stackoverflow
Solution 8 - JavaenoderView Answer on Stackoverflow
Solution 9 - JavagrandmaximumView Answer on Stackoverflow
Solution 10 - JavaUmAnusornView Answer on Stackoverflow
Solution 11 - JavaKushagra PandeView Answer on Stackoverflow
Solution 12 - JavaAdarshView Answer on Stackoverflow
Solution 13 - JavaSuhas KaranthView Answer on Stackoverflow
Solution 14 - JavaDan GravellView Answer on Stackoverflow
Solution 15 - JavaAdityaView Answer on Stackoverflow
Solution 16 - JavasamView Answer on Stackoverflow