@InjectMocks 后为空 [英] Null after @InjectMocks

查看:1280
本文介绍了@InjectMocks 后为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 JUnit 进行单元测试时,我在传递依赖项时遇到了一些麻烦.

I am having some troubles passing a dependency while unit testing with JUnit.

考虑这些代码片段:

这是我要测试的类的依赖注入,我们称之为控制器.

This is the dependacy injecton into the class which i want to test, lets call it Controller.

@Inject private FastPowering fastPowering;  

这是单元测试:

@RunWith(MockitoJUnitRunner.class)
public class ControllerTest {

@Mock
FastPowering fastPower;

@InjectMocks
Controller controller;

@Test
public void test() {
    assertEquals(
            (controller.computeAnswer(new BigDecimal(2), 2)).longValue(),
            (long) Math.pow(2, 2));
    }
}

fastPower 似乎为空,请解释如何解决这个问题.空指针异常,因为在 .computeAnswer 方法中调用了@injected 字段(fastPower))

It seems that fastPower is null, please explain how to fix that. Null pointer exception , because of calling the @injected field (fastPower) inside the .computeAnswer method)

解决了我应该阅读@Mock 和@Spy 之间的区别...

Solved i should have read about the difference between @Mock and @Spy...

由于有很多评论,我在解决方案中添加了更多上下文

Due to a lot of comments I am adding some more context to the solution

不同之处在于,在模拟中,您正在创建一个完整的模拟或假对象,而在 spy 中,有真实的对象,而您只是在监视或存根它的特定方法.而在 spy 对象中,当然,因为它是一个真正的方法,当你不存根该方法时,它会调用真正的方法行为.

The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it. While in spy objects, of course, since it is a real method, when you are not stubbing the method, then it will call the real method behavior.

如果 fastPower 被注释为 @Mock 它的方法是虚拟的,但 controller.computeAnswer 依赖于它们来计算.必须提供行为.

If fastPower is annotated as @Mock it's methods are dummy, yet controller.computeAnswer depends on them to compute. One must provide behaviour.

如果在没有存根的情况下使用 spy,则正在执行 fastPower 的真正实现,最终返回所需的值.

If spy is used without stubbing then the real implementation of fastPower is being executed which eventually returns desired value.

另一种选择是使用真正的FastPowering 实例

Another option is to use a real FastPowering instance

https://github.com/mockito/mockito/wiki/Using-Spies-(and-Fakes)https://github.com/mockito/mockito/wiki/Mocking-Object-创作

还有一些 stackoverflow 线程概述了区别模拟框架中的模拟与间谍

And some stackoverflow thread outlining the difference Mocking vs. Spying in mocking frameworks

简短回答:将 @Mock 替换为 @Spy 并且应该可以正常工作

Short Answer: Replace @Mock with @Spy and should be working fine

推荐答案

使用 MockitoAnnotations.initMocks 来启动 @Mock@InjectMocks对象.您的测试将类似于:

Use MockitoAnnotations.initMocks to initiate the @Mock and @InjectMocks objects. Your test would look something like:

@Mock
FastPowering fastPower;

@InjectMocks
Controller controller;

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

@Test
public void test() {
    ....
}

这篇关于@InjectMocks 后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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