java - 断言一个模拟的静态方法被多次调用,每次都有一个特定的参数
问题描述
不是重复 我已经看过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 ...
}
}
解决方案
Mockito 使得在 3.4.0 版本之后在没有外部 Powermock 的情况下模拟静态方法成为可能。下面是一些关于如何实现这一点的好文章。
- 文章 - https://wttech.blog/blog/2020/mocking-static-methods-made-possible-in-mockito-3.4.0/
- Mockito Wiki - 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());
推荐阅读
- angular - Angular 应用程序部署到 firebase:404 错误
- python - Atom Hydrogen - 安装干净的 python 后的多个内核
- c++ - TrueType 字体缩放会导致文本模糊?
- javascript - 将鼠标悬停在按钮上可加快视频速度,当不悬停按钮时,视频会恢复到相同的速度
- wordpress - nginx 和 wordpress 不同的 docker-compose 文件
- python - 如何将正则表达式对象与python中的列表进行比较?
- php - PHP:复选框数组中的选中属性
- google-chrome-extension - 如何为浏览器扩展提供所有文本数据输入到该浏览器?
- javascript - React 类组件方法:我的代码是必须的吗?
- javascript - 在(Vue,React)中导出带有子模块的模块的最佳方法是什么