assert一个模拟的静态方法被多次调用,每次调用都有一个特定的参数

bogh5gae  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(501)

我已经看过多次调用的mocking静态方法,但这个问题与我的不同,他在寻求部分mocking。
我想要什么

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 ...
    }
}
z18hc3ub

z18hc3ub1#

mockito使得在没有外部powermock的情况下模拟3.4.0版本之后的静态方法成为可能。下面是一些关于如何实现这一点的好文章。
第-https://wttech.blog/blog/2020/mocking-static-methods-made-possible-in-mockito-3.4.0/
mockito维基-https://javadoc.io/static/org.mockito/mockito-core/3.6.28/org/mockito/mockito.html#48.

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

相关问题