首页 > 解决方案 > 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}')))

我正在尝试使用matchesMatcher 但失败并出现以下错误:

预计 1 个匹配者,2 个记录

我应该怎么做才能通过正则表达式匹配地图值?

标签: dictionarygroovymockito

解决方案


首先: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 之一。


推荐阅读