【问题标题】:Static method mock in parent class for JUnit using EasyMock [duplicate]使用 EasyMock 在 JUnit 的父类中模拟静态方法 [重复]
【发布时间】:2014-03-02 11:29:59
【问题描述】:

我在 JUnit 测试中使用 EasyMock。我想模拟父类中存在的静态方法。例如:

Class A {
    public void testOne() {
        Map map = StaticClass.method();
        // using map code here ...
    }
}

Class B extends A {
    public void testTwo(){
        testOne();`
    }
}

现在,我正在为 B 类编写 JUnit 测试,我想在 A 类中模拟 StaticClass.method()。 如何实现?

【问题讨论】:

  • 到目前为止您尝试过什么?另外,请考虑是否真的需要调用静态方法,或者是否可以将StaticClass 的实例传递给A 类。

标签: java junit easymock


【解决方案1】:

我建议(按我的喜好顺序):

  1. 用具体的实现包装它并模拟具体的类
  2. 使用受保护的方法并使用可测试的类扩展类
  3. 使用PowerMock

选项 1 - 具体实施

public class StaticClassWrapper() {
   public Map method() {
      return StaticClass.method();
   }
}

选项 2 - 可测试类

public class A {
    public void testOne() {
       Map map = method();
    }

    protected Map method() {
      return StaticClass.method();
    }
}

在您的测试中,您需要创建 TestableA 并在其上运行测试(而不是在 A 上运行测试):

public class TestableA {
    protected Map method() {
       // return a mock here
    }
}

您最后一个(也是最不喜欢的)选项是使用PowerMock。它可以与EasyMock 一起使用以模拟静态调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多