19

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");
2
  • I would recommend thinking carefully before writing this type of test, arguments against checking the value of private variable summarised here: stackoverflow.com/questions/2981476/…
    – codebox
    Commented Jan 19, 2015 at 15:07
  • The real test is a bit more complex and involves hibernate, session and sessionfactory, i try to check our dbInterface without having to initialize complete hibernate stuff. In most methods we modify an objects state and have no real input/output functionality.
    – Gobliins
    Commented Jan 19, 2015 at 15:15

1 Answer 1

28

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

4
  • Yes i somehow overlooked the code sample on the page. Your answer is correct
    – Gobliins
    Commented Jan 19, 2015 at 15:03
  • 1
    I like the "Arrange, Act, Assert" comments. I use "Setup, Test, Validate" but like the ring of the 3 As. Commented Nov 7, 2016 at 19:30
  • I actually switched from S-T-V to A-A-A. The alliteration indeed makes it sound nice. But most importantly (with either abbreviation): it helps you structure your test, making it harder to accidentally test your mock instead of your SUT. I've seen that happen - due to the three phases being mixed.
    – mthmulders
    Commented Nov 8, 2016 at 6:56
  • 3
    answer to the exercise for private static bar: Foo foo = Whitebox.getInternalState(Bar.class, "foo"); for you can get static field directly through class rather than instance :) Commented Oct 17, 2017 at 10:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.