PowerMock访问私有成员

时间:2015-01-19 14:57:05

标签: java junit mockito private powermock

阅读后: https://code.google.com/p/powermock/wiki/BypassEncapsulation 我意识到,我没有得到它。

参见本例:

public class Bar{
   private Foo foo;

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

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

注意:
我不想要的是使用额外的get方法修改代码。

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

解决方案:

 Whitebox.getInternalState(bar, "foo");

1 个答案:

答案 0 :(得分:19)

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

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)));
    }
}

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