Monday, July 22, 2013

Mock private field and private method using PowerMock

Example 

public class PrivateObject {

    private String privateString;

    public PrivateObject(String privateString) {
this.privateString = privateString;
    }

    private String getPrivateString() {
return this.privateString;
    }

}


Mock using PowerMock

// class instance
PrivateObject instance = new PrivateObject ();

// mock private field/variable
MemberModifier
                .field(PrivateObject .class, "privateString").set(
instance , "hellomock");

// mock private method
MemberModifier
.stub(MemberMatcher.method(PrivateObject .class,
"getPrivateString"))
.toReturn(
"Power Mock");