【问题标题】:EasyMock - Expecting a method call which is staticEasyMock - 期待一个静态的方法调用
【发布时间】:2018-03-21 00:28:46
【问题描述】:

如何使用 EasyMock 来测试不能被覆盖的静态函数?我有一个大型测试套件类,我在测试套件中部分模拟了一个对象“A”。当我模拟我的对象“A”时,有什么办法可以期待这些接受参数的静态方法调用?

为了代码的缘故,类 A 和 B 必须保持在它们当前的位置,并且由于外部依赖关系而不能重新排列。 “A”类从“B”类调用 bar()。我需要能够模拟方法 foo() 或方法 bar(),但是它们是静态的并且接受参数。

有问题的班级:

class A extends B {
    public static void foo(args...) {
        ...
        bar(args...);
    }
}

class B {
    public static void bar(args...) {
        ....
    }
}

【问题讨论】:

标签: java unit-testing easymock


【解决方案1】:

我认为你不能用 easymock 做到这一点。

在此处查看类似问题:

How do I mock static methods in a class with easymock?

【讨论】:

  • 谢谢。经过进一步研究,您是正确的。我希望这样做有一个 hacky 方法。
  • 没有。您需要在 EasyMock 之上使用 Powermock 才能做到这一点
  • @Henri - 您能否建议我们如何使用 PowerMock 做到这一点?
【解决方案2】:

给你。但是阅读 PowerMock 文档应该会在 5 分钟内给您相同的答案。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ B.class})
public class MyTest {

  @Test
  public void test() {
    mockStatic(B.class); // Mock static methods on B
    B.bar(4); // Record a static call to B.bar expecting 4 in argument

    replay(B.class); // Go in replay mode

    A.foo(4); // Call foo that will then call bar(4)

    verify(B.class); // Verify that B.bar(4) was indeed called 
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多