如何使用PowerMockito或Mockito模拟超类中的“ getServerName”方法?
public class A extends B{
public static String builder(){
return new A().get();
}
private String get() {
return this.getServerName();
}
}
public abstract class B{
protected String getServerName(){
return "Server 1";
}
}
记住我是通过静态方法执行的:
public static void main (String [] args) {
String name = A.builder();
}
答案 0 :(得分:0)
我能够解决!
您必须监视A类
A a = PowerMockito.spy(new A());
PowerMockito.when(a, "getServerName")
.thenReturn("Mock Value");
// Here is the movement, you have to replace the original constructor.
PowerMockito.whenNew(A.class).withNoArguments().thenReturn(a);
System.out.print(A.builder());
--> Mock Value