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");

9 comments:

  1. It's really good for methods where passing parameters are not important, but how invoke the private method with specific argument(s)?

    ReplyDelete
  2. You saved my time..Thanks :)
    keep up the good work going.

    ReplyDelete
  3. Very helpful.
    But can you tell me a way by which we can provide arguments to the mocked private function.

    ReplyDelete