下面是我的课
public class SomeClass {
public ReturnType1 testThisMethod(Type1 param1, Type2 param2) {
//some code
helperMethodPublic(param1,param2);
//more code follows
}
public ReturnType2 helperMethodPublic(Type1 param1, Type2 param2) {
//some code
}
}
所以在上面的类中测试 testThisMethod() 时,我想部分模拟 helperMethodPublic()。
截至目前,我正在执行以下操作:
SomeClass someClassMock =
PowerMock.createPartialMock(SomeClass.class,"helperMethodPublic");
PowerMock.expectPrivate(someClassMock, "helperMethodPublic, param1, param2).
andReturn(returnObject);
编译器不会提示。所以我尝试运行我的测试,当代码命中 helperMethodPublic() 方法时,控件进入该方法并开始执行其中的每一行代码。我该如何防止这种情况发生?
最佳答案
另一个不依赖模拟框架的解决方案是在您的测试中定义的匿名子类中覆盖“helperMethodPublic”:
SomeClass sc = new SomeClass() {
@Override
public ReturnType2 helperMethodPublic(Type1 p1, Type2 p2) {
return returnObject;
}
};
然后当您在测试中使用此实例时,它将运行原始版本的“testThisMethod”和覆盖版本的“helperMethodPublic”
关于java - 如何使用 PowerMock 部分模拟公共(public)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10758166/