我在工作测试中有以下内容:
when(client.callApi(anyString(), isA(Office.class))).thenReturn(responseOne);
请注意,客户端是类客户端的模拟。
我想更改“isA(Office.class)”以告诉它匹配 Office 实例的“id”属性为“123L”的位置。如何在模拟对象的方法中指定我想要一个特定的参数值?
编辑:不是重复的,因为我试图在“何时”使用它并且链接的问题(以及我发现的其他资源)在“验证”和“断言”上使用 ArgumentCaptor 和 ArgumentMatcher。我在想我实际上不能做我正在尝试的事情,我会尝试另一种方式。当然,我愿意以其他方式展示。
最佳答案
按要求重新打开,但解决方案(使用 ArgumentMatcher)与 the one in the linked answer 相同.当然,您不能在 stub 时使用 ArgumentCaptor
,但其他一切都是一样的。
class OfficeWithId implements ArgumentMatcher<Office> {
long id;
OfficeWithId(long id) {
this.id = id;
}
@Override public boolean matches(Office office) {
return office.id == id;
}
@Override public String toString() {
return "[Office with id " + id + "]";
}
}
when(client.callApi(anyString(), argThat(new IsOfficeWithId(123L)))
.thenReturn(responseOne);
因为 ArgumentMatcher 只有一个方法,您甚至可以在 Java 8 中将其设为 lambda:
when(client.callApi(anyString(), argThat(office -> office.id == 123L))
.thenReturn(responseOne);
如果您已经在使用 Hamcrest,您可以使用 MockitoHamcrest.argThat
调整 Hamcrest 匹配器,或使用内置的 hasProperty
:
when(client.callApi(
anyString(),
MockitoHamcrest.argThat(
hasProperty("id", equalTo(123L)))))
.thenReturn(responseOne);
关于java - 检查特定对象属性值时的 Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42587115/