arrays - 对数组元素使用 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
方法中验证它们。
解决方案
您可以使用 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);
推荐阅读
- android - 颤振运行返回错误无法创建jar文件
- php - php从不同的接口实现相同的功能
- camunda - 使用 REST API 部署 .html 嵌入式表单和 .bpmn 模型
- php - 错误:事物不是 itemReviewed 属性的已知有效目标类型
- javascript - 如何将字段名称传输到 React json 模式 ui 中的组:组嵌套对象场景
- python - 用 Python 实现网络爬虫
- python - 用于禁用 base64 并删除 MIME 版本的 python3 电子邮件
- bash - 在 bash 脚本期间获取用户输入
- r - 用多列重塑 long 会导致错误
- python - 尝试将列表中的双字名称与用户输入匹配时如何处理它们?