Elad Benda2
Elad Benda2

Reputation: 15472

mock instance is null after @Mock annotation

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?

Upvotes: 151

Views: 205896

Answers (20)

Valkyrie006
Valkyrie006

Reputation: 11

My Code

  1. It had JUnit version ->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <scope>test</scope>
    <version>5.0.0</version>
</dependency>
  1. Was running on java 8

Solution

Change @Test to import from -

import org.junit.jupiter.api.Test;

instead of -

import org.junit.Test;

Upvotes: 1

F0cus
F0cus

Reputation: 625

our application uses JUNIT5 , same issue occured. I replaced @Mock with @InjectMocks - then issue was resolved

Upvotes: 0

Smart Coder
Smart Coder

Reputation: 1738

Junit 5 with InjectMocks. Based on above suggestion https://stackoverflow.com/a/55616702/2643815

 @ExtendWith(MockitoExtension.class)
public class MyClientTest {
@Mock
    Environment environment;
    @Mock
    ClassCreator classCreator;

    @InjectMocks
    MyClient myClient;


    @Test
    public void mytest() {
            myClient = new MyClient(environment, classCreator);
            
            }
            }

Upvotes: 1

Divyanshu Singh
Divyanshu Singh

Reputation: 87

My issue was that I was trying to mock an object which was final in my service. Just needed to remove final and it worked.

Upvotes: 1

Aditya
Aditya

Reputation: 13

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

Upvotes: 0

grandmaximum
grandmaximum

Reputation: 131

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.

Upvotes: 3

Adarsh
Adarsh

Reputation: 99

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.

Upvotes: 7

Kushagra Pande
Kushagra Pande

Reputation: 27

For me it worked when I added :

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

Upvotes: 2

Dan Gravell
Dan Gravell

Reputation: 8240

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?

Upvotes: 0

amanatee
amanatee

Reputation: 361

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.

Upvotes: 12

Suhas Karanth
Suhas Karanth

Reputation: 57

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>

Upvotes: 0

Ganesh Satpute
Ganesh Satpute

Reputation: 3941

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!

Upvotes: 7

Stefan Birkner
Stefan Birkner

Reputation: 24520

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 {
    // ...
  }
}

Upvotes: 73

Gjera
Gjera

Reputation: 1247

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>

Upvotes: 94

Rammgarot
Rammgarot

Reputation: 1667

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;

Upvotes: 44

UmAnusorn
UmAnusorn

Reputation: 11124

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

Upvotes: 1

Oliver
Oliver

Reputation: 1269

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.

Upvotes: 4

sam
sam

Reputation: 123

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.

Upvotes: -4

Roland Weisleder
Roland Weisleder

Reputation: 10511

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.

Upvotes: 147

enoder
enoder

Reputation: 91

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

Upvotes: 4

Related Questions