dictionary - Mockito:验证参数是使用正则表达式模式的 Map
问题描述
我有一个执行以下操作的函数:
mock_object.install_tool name:"Python27x32', type:"CustomTool'
在测试功能时,我想验证以下内容:
verify(mock_object, times(1)).install_tool(argThat(hasEntry('name')))
verify(mock_object, times(1)).install_tool(argThat(hasValue('Python\\d{2}x\\d{2}')))
我正在尝试使用matches
Matcher 但失败并出现以下错误:
预计 1 个匹配者,2 个记录
我应该怎么做才能通过正则表达式匹配地图值?
解决方案
首先:org.hamcrest.Matchers.hasEntry
需要 2 个参数,只有一个参数的代码无效
hasEntry('name') // no such overload
hasEntry
有2个重载:
hasEntry(K key, V value)
hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher)
我们希望在键中进行值比较,在值中进行正则表达式。因此,我们使用:
- 钥匙:
Matchers.is(T value)
- 值:之一
Matchers.matchesPattern(java.lang.String regex)
Matchers.matchesRegex(java.lang.String regex)
不幸的是,在 Java 中,我们需要额外的未经检查的强制转换。参见Mockito、argThat 和 hasEntry
我们最终得到:
Matcher<String> mapKeyMatcher = Matchers.is("name");
Matcher<String> mapValueMatcher = Matchers.matchesPattern("Python\\d{2}x\\d{2}");
verify(mock_object, times(1)).install_tool(
(Map<String, String>) argThat(
hasEntry(mapKeyMatcher, mapValueMatcher)
)
);
Hamcrest 更新
Mockito 带有自己的一组匹配器:org.mockito.ArgumentMatchers
但不幸的是它没有 Map 匹配器。幸运的是 Hamcrest 做到了,这就是你首先使用 Hamcrest 的原因。
要使 Hamcrest 匹配器适应您使用的 Mockito 匹配器argThat(YOUR_HAMCREST_MATCHER)
我们决定使用的地图匹配器具有以下签名:
hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher)
两个参数都是 Hamcrest 匹配器。您不能从 Mockito 传递正则表达式匹配器,您需要使用 Hamcrest 之一。
推荐阅读
- javascript - FCM 通知
- apache-spark - Apache kafka 没有重新平衡负载
- reactjs - React 功能组件中的 TypeScript 检查
- javascript - 立即留下一个包含 async-await 承诺的 for 循环
- python - 在 Python 中将数据框的值转换为句子
- r - rbind R 中存在的任何内容
- angular - 在后台Angular工作之前禁用按钮?
- pdf - Telerik,导出到 pdf 操作抛出错误,NotSupportedException: Font Century Gothic 9 Regular is not supported
- r - 函数的奇怪结果
- javascript - 尝试使用 React Route 和 Webpack 实现 React “Lazy” 路由以进行代码拆分