本文介绍了PowerMock访问私人会员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读后:

i意识到,我不明白。

After reading:https://code.google.com/p/powermock/wiki/BypassEncapsulationi realized, i don't get it.

参见本例:

public class Bar{
   private Foo foo;

   public void initFoo(){
       foo = new Foo();
   }
}

如何访问私人会员 foo 使用PowerMock(例如,验证 foo 是否为空)?

How can i access the private member foo by using PowerMock (For example to verify that foois not null)?

注意:

我不想要的是用额外的修改代码方法。

编辑:

我意识到我错过了示例代码块带解决方案的链接页面。


I realized that i missed a sample code block on the linked page with the solution.

解决方案:

 Whitebox.getInternalState(bar, "foo");


推荐答案

这应该像编写以下测试类一样简单:

That should be as simple as writing the following test class:

public class BarTest {
    @Test
    public void testFooIsInitializedProperly() throws Exception {
        // Arrange
        Bar bar = new Bar();

        // Act
        bar.initFoo();

        // Assert
        Foo foo = Whitebox.getInternalState(bar, "foo");
        assertThat(foo, is(notNull(Foo.class)));
    }
}

添加正确(静态)导入保留为练习给读者:)。

Adding the right (static) imports is left as an exercise to the reader :).

这篇关于PowerMock访问私人会员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 08:08