PowerMock访问私人会员
阅读后: https : //code.google.com/p/powermock/wiki/BypassEncapsulation我意识到,我不明白。
请参阅此示例:
public class Bar{ private Foo foo; public void initFoo(){ foo = new Foo(); } }
如何通过使用PowerMock访问私有成员foo
(例如,validationfoo
不为null)?
注意:
我不想要的是使用额外的get
方法修改代码。
编辑:
我意识到我错过了链接页面上的示例代码块和解决方案。
解:
Whitebox.getInternalState(bar, "foo");
这应该像编写以下测试类一样简单:
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))); } }
添加正确的(静态)导入留给读者:)。