代码之家  ›  专栏  ›  技术社区  ›  ROMANIA_engineer Alexey

对数组元素使用mockito匹配器

  •  1
  • ROMANIA_engineer Alexey  · 技术社区  · 7 年前

    我有这样一个方法:

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

    我可以为它指定一种行为,比如:

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

    但我想说得更具体一些 “任何包含2个元素的数组,其中第二个元素为空” 是的。所以,作为“伪代码”,我想使用:

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

    这在莫基托有可能吗?

    作为一个解决办法我可以用 verify 为了检查元素的类型 但我想在 when 方法。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Sergii Bishyr    7 年前

    你可以用mockito argTaht 使用你的定制火柴。 在您的情况下,您可以这样实现它:

    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);