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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:28:37  来源:igfitidea点击:

PowerMock access private members

javajunitmockitoprivatepowermock

提问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 fooby using PowerMock (For example to verify that foois not null)?

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

Note:
What i don't want is modifying the code with extra getmethods.

注意:
我不想要的是用额外的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 :).

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