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

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

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

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

我该如何嘲笑 a(x,y) 方法?
我希望测试执行的伪代码:

  1. class TestA {
  2. @Test
  3. public void test_method_a_is_called_x_numbers_of_times_each_with_specific_parameters() {
  4. SUT.exercise() // I need to verify SUT's behavior by observing the SUT's calls to `a(x,y)`
  5. // I want to somehow be able to assert: (Psuedo code)
  6. // First call to `a(x,y)` was: a(0,0)
  7. // Second call to `a(x,y)` was: a(0,1)
  8. // Third call to `a(x,y)` was: a(0,0)
  9. // Fourth call to `a(x,y)` was: a(4,2)
  10. // You get the idea ...
  11. }
  12. }
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.

  1. assertEquals("foo", Foo.method());
  2. try (MockedStatic mocked = mockStatic(Foo.class)) {
  3. mocked.when(Foo::method).thenReturn("bar");
  4. assertEquals("bar", Foo.method());
  5. mocked.verify(Foo::method);
  6. }
  7. assertEquals("foo", Foo.method());

相关问题