我的职能如下:
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次记录
如何通过regex匹配映射值?
发布于 2020-05-06 20:40:49
首先:org.hamcrest.Matchers.hasEntry需要两个参数,只有一个参数的代码无效
hasEntry('name') // no such overloadhasEntry有两个重载:
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, and 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,但不幸的是它没有地图匹配器。幸运的是,Hamcrest做到了,这就是为什么您首先使用Hamcrest。
要使Hamcrest匹配器适应Mockito匹配器,可以使用argThat(YOUR_HAMCREST_MATCHER)
我们决定使用的地图匹配器具有以下签名:
hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher)这两个论点都是Hamcrest的对立面。您不能从Mockito通过regex matcher,您需要使用Hamcrest one。
https://stackoverflow.com/questions/61641331
复制相似问题