Example
public class PrivateObject {
private String privateString;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
private String getPrivateString() {
return this.privateString;
}
}
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");
Thank you. Very helpful.
ReplyDeleteIt's really good for methods where passing parameters are not important, but how invoke the private method with specific argument(s)?
ReplyDeleteThat was really helpful
ReplyDeleteYou saved my time..Thanks :)
ReplyDeletekeep up the good work going.
superb
ReplyDeleteVery helpful.
ReplyDeleteBut can you tell me a way by which we can provide arguments to the mocked private function.
Great work Sunil!
ReplyDeleteJust sent you an email on Linkedin!
Deletethis is really helpfull!!!
ReplyDelete