使用 Mockito 将模拟对象注入在测试中声明为字段的待测试对象不起作用?

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

问题描述

限时送ChatGPT账号..

我有一堂课,我正在向我的服务中注入一个代理.

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 注释可以使用 Constructor injection 机制,这是您的 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 注入Field 注入(请参阅 docs 顺便说一句),但您需要一个无参数构造函数才能使用它们.

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) 所以 @Mock 注释无效
  • 即使满足上述条件,您的示例也会失败,因为 mockProxy 将在 构建测试并尝试使用您的 服务 之后初始化在测试类构造过程中初始化,因此它接收到 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 将模拟对象注入在测试中声明为字段的待测试对象不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何使用 Mockito 部分模拟 HttpServletRequest 下一篇:Mockito - 如何验证从未调用过模拟

相关文章