【问题标题】:How to mock in method superclass, starts with static method?如何在方法超类中模拟,从静态方法开始?
【发布时间】:2019-01-21 20:08:34
【问题描述】:

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

【问题讨论】:

标签: java junit mockito powermockito


【解决方案1】:

我解决了!

你必须监视 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多