首页 > 解决方案 > 断言一个模拟的静态方法被多次调用,每次都有一个特定的参数

问题描述

不是重复 我已经看过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 ...
    }
}

标签: javaunit-testingtestingmockingpowermockito

解决方案


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());

推荐阅读