【问题标题】:assert a mocked static method is called multiple times each with a specific argument断言一个模拟的静态方法被多次调用,每次都有一个特定的参数
【发布时间】:2020-12-17 18:38:40
【问题描述】:

不重复 我已经看过Mocking static method that is called multiple times,但是这个问题与我的不同之处在于他正在寻求部分嘲笑

我想要什么

class A {
   public static void a(int x, int y);   // <-- mock this static method
}

如何模拟a(x,y) 方法?

我希望我的测试执行的伪代码:

class TestA {
    @Test
    public void test_method_a_is_called_x_numbers_of_times_each_with_specific_parameters() {
        SUT.exercise()  // I need to verify SUT's behavior by observing the SUT's calls to `a(x,y)`

        // I want to somehow be able to assert: (Psuedo code)
        // First  call to `a(x,y)` was:   a(0,0)
        // Second call to `a(x,y)` was:   a(0,1)
        // Third  call to `a(x,y)` was:   a(0,0)
        // Fourth call to `a(x,y)` was:   a(4,2)

        // You get the idea ...
    }
}

【问题讨论】:

  • 为什么你在嘲笑?此方法实际上不会对您可以实际测试或观察的任何工件做任何事情。如果它被调用,那么这意味着它触及了您可以观察到的其他一些外部静态工件。在这种情况下,绝对没有什么可观察到的副作用,而嘲弄对您没有任何好处。
  • @Makoto 在我的例子中,a() 写入文件。我想通过模拟a() 来避免处理 i/o,然后断言它是使用预期参数调用的。
  • 文件很简单。在 JUnit 4 中,您可以设置 TemporaryFolder 规则并设置要写入的内容,以验证正在写入文件。事实上,这会带来更好的整体测试,因为您可以证明文件实际上是在编写的并且它具有您关心的值,而不是两者都不完成的模拟。
  • @Makoto 我的实际情况有点复杂,我有理由暂时放弃它。我现在正尝试按照我的问题所述做,看看与你刚才所说的比较。

标签: java unit-testing testing mocking powermockito


【解决方案1】:

Mockito 在 3.4.0 版本之后可以在没有外部 Powermock 的情况下模拟静态方法。下面是一些关于如何实现这一点的好文章。

 assertEquals("foo", Foo.method());
 try (MockedStatic mocked = mockStatic(Foo.class)) {
    mocked.when(Foo::method).thenReturn("bar");
    assertEquals("bar", Foo.method());
    mocked.verify(Foo::method);
 }
 assertEquals("foo", Foo.method());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2014-05-05
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多