手动实例化@InjectMock带注释的字段 [英] Manually instantiating the @InjectMock annotated field

查看:445
本文介绍了手动实例化@InjectMock带注释的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了一些博客,以了解Mockito批注如何工作的基础知识.

但是我面临着一个疑问,何时去手动实例化带有@InjectMocks的字段,即

@InjectMocks
A a = new A();

什么时候依靠MockitoAnnotations.initMocks()功能执行相同操作:

@InjectMocks
A a;

这是否取决于我们用来运行测试用例的JunitTestRunner还是取决于Mockito框架版本?

解决方案

感谢您的宝贵想法. 但是,对于为什么应该通过调用MockitoAnnotations.initMocks()来处理实例化的情况,为什么仍然要手动实例化带有@InjectMocks注释的字段的问题仍然没有得到回答.

尝试运行测试文件时出现以下错误:

由以下原因引起:org.mockito.exceptions.base.MockitoException:用@InjectMocks注释的字段'student'为空. 请确保在之前 MockitoAnnotations.initMocks();创建实例. 正确用法示例:

class SomeTest {
    @InjectMocks private Foo foo = new Foo();

    @Before public void setUp() {
        MockitoAnnotations.initMock(this);

我进一步搜索,发现如果使用的是较旧版本的Mockito框架,则会引发该错误.

http://myshittycode.com/category/testing/mockito/

I have gone through some of the blogs in order to understand the basics of how Mockito annotations work.

However I am facing a doubt as to when does one go for manually instantiating the field annotated with @InjectMocks i.e

@InjectMocks
A a = new A();

And when does one rely on MockitoAnnotations.initMocks() functionality to do the same :

@InjectMocks
A a;

Does this depend on the JunitTestRunner that we employ to run the test cases or is it dependent on the Mockito framework version?

解决方案

Thanks for your valuable thoughts. But still it doesn't answer the question as to why one goes for manually instantiating the field annotated with @InjectMocks when the instantiation should be handled by a call to MockitoAnnotations.initMocks().

I get the following error when trying to run the test file :

Caused by: org.mockito.exceptions.base.MockitoException: Field 'student' annotated with @InjectMocks is null. Please make sure the instance is created before MockitoAnnotations.initMocks(); Example of correct usage:

class SomeTest {
    @InjectMocks private Foo foo = new Foo();

    @Before public void setUp() {
        MockitoAnnotations.initMock(this);

I searched further and found out that the error is thrown if one is using an older version of Mockito framework.

http://myshittycode.com/category/testing/mockito/

这篇关于手动实例化@InjectMock带注释的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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