Java @Mock 注释后模拟实例为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29590621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:16:11  来源:igfitidea点击:

mock instance is null after @Mock annotation

javaunit-testingjunitmockingmockito

提问by Elad Benda2

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:

但我得到 NullPointerException 为:

Mockito.when(routingClientMock.

Mockito.when(routingClientMock.

what am i missing?

我错过了什么?

采纳答案by Roland Weisleder

When you want to use the @Mockannotation you should use the MockitoJUnitRunner

当您想使用@Mock注释时,您应该使用MockitoJUnitRunner

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {

    @Mock
    private IRoutingObjHttpClient routingClientMock;

    @Test
    public void testSendRoutingRequest() throws Exception {
        // ...
    }

}

See also this tutorial.

另请参阅本教程

回答by enoder

  1. You should use @RunWith(SpringJUnit4ClassRunner.class)at your class
  2. You have to call MockitoAnnotations.initMocks(this);in @Before method
  1. 你应该@RunWith(SpringJUnit4ClassRunner.class)在你的课堂上使用
  2. 你必须MockitoAnnotations.initMocks(this);在@Before 方法中调用

回答by Stefan Birkner

You have three options for activating the @Mockannotation: MockitoRule, MockitoJUnitRunner, MockitoAnnotations.initMocks(this). IMHO using the MockitoRuleis the best one, because it lets you still choose another runner like e.g. Parameterized.

您可以使用三个选项来激活@Mock注释:MockitoRule、MockitoJUnitRunner、MockitoAnnotations.initMocks(this)。恕我直言,使用MockitoRule是最好的,因为它可以让您仍然选择另一个跑步者,例如Parameterized

Use the MockitoRule

使用MockitoRule

public class MockitoTest {

  @Mock
  private IRoutingObjHttpClient routingClientMock;

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

  @Test
  public void testSendRoutingRequest() throws Exception {
    // ...
  }
}

Use the MockitoJUnitRunner

使用MockitoJUnitRunner

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {

  @Mock
  private IRoutingObjHttpClient routingClientMock;

  @Test
  public void testSendRoutingRequest() throws Exception {
    // ...
  }
}

Call MockitoAnnotations.initMocks(this)explicitly.

显式调用MockitoAnnotations.initMocks(this)

This can be done in qn @Beforemethod, in your own runner or in an own rule.

这可以在 qn@Before方法、您自己的跑步者或自己的规则中完成。

public class MockitoTest {

  @Mock
  private IRoutingObjHttpClient routingClientMock;

  @Before
  public void createMocks() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testSendRoutingRequest() throws Exception {
    // ...
  }
}

回答by sam

If you are also using PowerMock then

如果您还使用 PowerMock,那么

@RunWith(MockitoJUnitRunner.class)

can be replaced with

可以替换为

@RunWith(PowerMockRunner.class)

This will activate your @Mocksand enable the PowerMock functionality.

这将激活您@Mocks并启用 PowerMock 功能。

回答by UmAnusorn

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

尝试检查您正在调用的方法是否是最终方法。

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

Mockito 不能模拟 final 方法。https://github.com/mockito/mockito/wiki/FAQ

回答by Z3d4s

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.

例如,“org.easymock”包也有一个名为@Mock 的注释,当然,它不适用于 Mockito 特定设置。

回答by Rammgarot

If you use junit.jupiterwith @ExtendWith(MockitoExtension.class)for test class but mocks are null, ensure that @Testannotation is imported from

如果您使用junit.jupiterwith @ExtendWith(MockitoExtension.class)for 测试类但模拟为 null,请确保@Test

import org.junit.jupiter.api.Test;

instead of org.junit.Test;

代替 org.junit.Test;

回答by Gjera

Same problem can occur if you are using Junit5 since there is no more '@RunWith' annotation.

如果您使用 Junit5,可能会出现同样的问题,因为没有更多的“@RunWith”注释。

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

您还应该导入您的依赖项(Maven - pom.xml):

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>${mockito.version}</version>
    <scope>test</scope>
</dependency>