PowerMock access private members

Gobliins picture Gobliins · Jan 19, 2015 · Viewed 22.4k times · Source

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

Answer

mthmulders picture mthmulders · Jan 19, 2015

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