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");
Assume that this private method has to be unit tested for some reason. In order to do so, you have to use PowerMock's Whitebox. invokeMethod(). You give an instance of the object, method name as a String and arguments to call the method with.
PowerMock integrates with mocking frameworks like EasyMock and Mockito and is meant to add additional functionality to these – such as mocking private methods, final classes, and final methods, etc. It does that by relying on bytecode manipulation and an entirely separate classloader.
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
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 :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With