简体   繁体   English

PowerMock访问私有成员

[英]PowerMock access private members

After reading: https://code.google.com/p/powermock/wiki/BypassEncapsulation i 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)? 如何通过使用PowerMock访问私有成员foo (例如,验证foo不为null)?

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

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 :). 添加正确(静态)导入留给读者:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM