PowerMock access private members

2019-04-19 17:04发布

问题:

After reading: https://code.google.com/p/powermock/wiki/BypassEncapsulation i realized, i don't get it.

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 foois not null)?

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

Edit:
I realized that i missed a sample code block on the linked page with the solution.

Solution:

 Whitebox.getInternalState(bar, "foo");

回答1:

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 :).