Mockito:模拟私有字段初始化 [英] Mockito: Mock private field initialization

查看:722
本文介绍了Mockito:模拟私有字段初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何模拟正在内联初始化的字段变量?

How I can mock a field variable which is being initialized inline?

例如

class Test {
    private Person person = new Person();
    ...
    public void testMethod() {
        person.someMethod();
        ...
    }
}

我想要模拟 person.someMethod(),测试方法 - 测试#testMethod。

Here I want to mock person.someMethod() while testing method - Test#testMethod.

我需要模拟初始化人变量。任何线索?

for which I need to mock initialization of person variable. Any clue?

编辑:我不允许修改Person类。

I'm not allowed to modify Person class.

推荐答案

我已经找到了这个问题的解决方案,我忘了在这里发布。

I already found the solution to this problem which I forgot to post here.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {

@Mock
Person person;

@Test
public void testPrintName() throws Exception {
    PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
    Test test= new Test();
    test.testMethod();
    }
}

此解决方案的关键点是:

Key points to this solution are:


  1. 使用PowerMockRunner运行我的测试用例: @RunWith(PowerMockRunner.class)

指示Powermock准备 Test.class 以操纵私有字段: @PrepareForTest ({Test.class})

Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

最后模拟Person类的构造函数:

And finally mock the constructor for Person class:

PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments() .thenReturn(person);

这篇关于Mockito:模拟私有字段初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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