本文介绍了如何使用PowerMockito模拟私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为重复项提出的解决方案不是PowerMockito解决方案,因此不能回答此问题.此外,此问题在下面得到了合理的回答.

The solution proposed as a duplicate is not a PowerMockito solution and as a consequence does not answer this question. Further, this question IS answered legitimately below.

IDK(如果这是重复项还是不是重复项),但是我确定找不到有关的项目.我一直期望这真的很简单,因为通过反射它非常简单,但是我宁愿使用正确的工具来完成它.

IDK if this is a duplicate or not but I sure can't find the item in question if it is. I keep expecting this to be really simple, since it is pretty simple with reflection but I'd rather do it using the right tools.

说明:旧版代码.没有吸气剂/二传手.

Clarification: Legacy code. No getters / setters.

为此使用Whitebox是否正确?我认为这是超限",即内部API的一部分? ...或者那是严格的Mockito吗?

Is it correct to use Whitebox for this? I thought it was "Off Limits" i.e. part of the internal API? ...or was that strictly Mockito?

推荐答案

请参见Whitebox.setInternalState(...).

例如-给定的类A需要进行测试:

For example - given class A which needs to be tested:

public class A {
    private B b;

    public A() {
        b = new B();
    }

    public void doSomething() {
        b.doSomething();
    }

}

具有B的私有实例:

public class B {

    public void doSomething() {
        // some long running, resource intensive process...
        System.out.println("Real B.doSomething() was invoked.");
    }

}

然后Whitebox可用于设置A的私有状态,以便可以对其进行测试:

then Whitebox can be used to set the private state of A so it can be tested:

import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.reflect.Whitebox;

@RunWith(MockitoJUnitRunner.class)
public class ATest {

    @Mock
    private B b;

    private A a;

    @Before
    public void prepareTest() {
        doNothing().when(b).doSomething();

        a = new A();
        Whitebox.setInternalState(a, B.class, b);
    }

    @Test
    public void doSomething() {
        a.doSomething();
        verify(b).doSomething();
    }

}

这篇关于如何使用PowerMockito模拟私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:17