首页 > 解决方案 > 对数组元素使用 Mockito 匹配器

问题描述

我有这样的方法:

String m(String s, Object[] args);

我可以为它指定一个行为,例如:

when(x.m(
            eq("expected string"), 
            Matchers.<Object[]>any()
)).thenReturn(expectedValue);

但我想更具体一点,并且能够指定类似“任何具有 2 个元素且第二个元素为 null 的数组”之类的内容。因此,作为“伪代码”,我想使用:

when(x.m(
            eq("expected string"), 
            Matchers.<Object[]>any(){anyString(), isNull()}
)).thenReturn(expectedValue);

这在 Mockito 中可能吗?

作为一种解决方法,我可以使用verify它来检查该数组中元素的类型,但我想在when方法中验证它们。

标签: arraysmockitomatcher

解决方案


您可以使用 MockitoargTaht来使用您的自定义匹配器。在您的情况下,您可以像这样实现它:

when(x.m(anyString(), argThat((Object[] o) -> o.length == 2 && o[0] instanceof String && o[1] == null)))
                .thenReturn("mocked value");

当然,您可以添加更多验证并检查是否需要。现在,如果您这样称呼它,您将获得模拟值:

String mocked = x.m("string", new Object[]{"string", null});
assertEquals("mocked value", mocked);

任何其他调用都将返回null

String notMocked = x.m("string", new Object[]{"string", "string"});
assertNull(notMocked);

推荐阅读