Wednesday, December 18, 2013

Performing unit test on non-public method with PowerMockito

Recently I’m running a series of unit testing on my own works. I found out that it is quite difficult for me because my code consists of abstract classes, protected fields and protected methods. I’ve been using Java Reflection on this issue before I found the solution on PowerMockito. Somehow, I find it easier to implement it using PowerMockito due to the number of LOC is smaller and also it is much more expensive as I read in this post.

Here is the details implementation on accessing private method through PowerMockito.
objectUnderTest = PowerMockito.spy(new TheRealImplementation());

PowerMockito.doNothing()
            .when(objectUnderTest, PowerMockito.method(TheTargetClass.class, "thePrivateMethod"))
            .withNoArguments();

Assuming TheRealImplementation class is as shown below:
public class TheRealImplementation {

    private void thePrivateMethod() {
        ...
        ...
    }
    ...
}

No comments: