如何在方法超类中模拟,从静态方法开始?

时间:2019-01-21 20:08:34

标签: java junit mockito powermockito

如何使用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();
}

1 个答案:

答案 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