Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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");
like image 758
Gobliins Avatar asked Jan 19 '15 14:01

Gobliins


People also ask

How do I make a private call in PowerMock?

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.

Can we mock private methods using powermockito?

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.

Can we write Mockito for private methods?

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.


1 Answers

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

like image 131
mthmulders Avatar answered Nov 02 '22 21:11

mthmulders