简体   繁体   中英

PowerMock access private members

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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