将模拟对象注入要在测试中声明为测试的对象的测试对象使用Mockito不起作用? [英] Injection of a mock object into an object to be tested declared as a field in the test does not work using Mockito?

查看:435
本文介绍了将模拟对象注入要在测试中声明为测试的对象的测试对象使用Mockito不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级,我正在为我的服务注入代理。

I have a class and I am injecting a proxy into my service.

Service service
{
    private ServiceProxy proxy;
    public Service(ServiceProxy proxy)
    {
        this.proxy = proxy; 
    }
}

对它的测试是:

ServiceTest
{
    @Mock
    ServiceProxy mockProxy;
    Service service = new Service(mockProxy);
}

如果我像这样初始化我的课程,我总是得到 NPE 当我想使用服务对象时。为什么 Mockito 这样做?有什么方法可以解决这个问题而不是在每次测试中声明它?

If I initialize my class like this I always get a NPE when I want to use the service object. Why does Mockito do this? What is an easy way around this instead of declaring it in each and every test?

推荐答案

如果您使用的是Mockito 1.9版本。 0或更高版本,达到你想要的最佳方式是这样的:

Provided you are using Mockito version 1.9.0 or later, the best way to achieve what you want is like this:

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private ServiceProxy proxy;

    @InjectMocks
    private Service service;

    @Test
    public void test() {
        assertNotNull(service);
        assertNotNull(proxy);
    }
}

首先是 @ RunWith(MockitoJUnitRunner.class)声明将导致@Mock和@InjectMocks注释自动工作,无需任何显式初始化。第二件事是从Mockito 1.9.0开始@InjectMocks注释可以使用构造函数注入机制,这是 Service 类的最佳选择。

First thing is the @RunWith(MockitoJUnitRunner.class) declaration which will cause @Mock and @InjectMocks annotation to work automatically without any explicit initialization. The second thing is that starting with Mockito 1.9.0 @InjectMocks annotation can use the Constructor injection mechanism which is the best option for your Service class.

@InjectMocks的其他选项是 Setter injection Field injection (参见 docs BTW)但你需要一个无参数的构造函数来使用它们。

Other options for @InjectMocks are Setter injection and Field injection (see docs BTW) but you'd need a no argument constructor to use them.

总结 - 您的代码无法正常工作,因为:

So summarizing - your code cannot work because:


  • 您没有使用MockitoJUnitRunner和MockitoAnnotations.initMocks(this)所以@模拟注释不起作用

  • 即使满足上述条件,您的示例也会失败,因为 mockProxy 将在构建测试后初始化尝试在测试类构造期间初始化 service ,因此它会收到null mockProxy 引用。

  • you are not using the MockitoJUnitRunner nor MockitoAnnotations.initMocks(this) so @Mock annotation takes no effect
  • even if above were satisfied your example would fail because mockProxy would be initialized after the test is constructed and your service is tried to be initialized during the test class construction, hence it receives null mockProxy reference.

如果出于某种原因,您不想使用@InjectMocks,唯一的方法是在测试方法体内或@Before带注释的setUp方法中构建 Service 对象。

If for some reason you don't want to use @InjectMocks, the only way is to construct your Service object within the test method body or within the @Before annotated setUp method.

这篇关于将模拟对象注入要在测试中声明为测试的对象的测试对象使用Mockito不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆