【问题标题】:Use Mockito matchers for array elements对数组元素使用 Mockito 匹配器
【发布时间】:2018-10-30 08:37:56
【问题描述】:

我有这样的方法:

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

这在 Mockito 中可行吗?

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

【问题讨论】:

    标签: arrays mockito matcher


    【解决方案1】:

    您可以使用 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2013-05-03
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多