Java PowerMock 访问私有成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28027445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerMock access private members
提问by Gobliins
After reading: https://code.google.com/p/powermock/wiki/BypassEncapsulationi realized, i don't get it.
阅读后:https: //code.google.com/p/powermock/wiki/BypassEncapsulation我意识到,我不明白。
See in this example:
在这个例子中看到:
public class Bar{
private Foo foo;
public void initFoo(){
foo = new Foo();
}
}
How can i access the private member foo
by using PowerMock (For example to verify that foo
is not null)?
如何foo
使用 PowerMock访问私有成员(例如验证foo
不为空)?
Note:
What i don't want is modifying the code with extra get
methods.
注意:
我不想要的是用额外的get
方法修改代码。
Edit:
I realized that i missed a sample code block on the linked page with the solution.
编辑:
我意识到我错过了解决方案链接页面上的示例代码块。
Solution:
解决方案:
Whitebox.getInternalState(bar, "foo");
采纳答案by mthmulders
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 :).
添加正确的(静态)导入留给读者作为练习:)。