我在工作测试中有以下内容:
when(client.callApi(anyString(), isA(Office.class))).thenReturn(responseOne);
Run Code Online (Sandbox Code Playgroud)
请注意,客户端是类Client的模拟.
我想更改"isA(Office.class)"以告诉它匹配Office实例的"id"属性为"123L"的位置.如何指定我想在模拟对象的方法中使用特定的参数值?
编辑:不重复,因为我试图在"when"上使用它,并且链接的问题(以及我发现的其他资源)在"verify"和"assert"上使用ArgumentCaptor和ArgumentMatcher.我想我实际上不能做我正在尝试的事情,并会尝试另一种方式.当然,我愿意以其他方式表现出来.
按要求重新打开,但解决方案(使用ArgumentMatcher)与链接答案中的解决方案相同.当然,你不能使用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);
Run Code Online (Sandbox Code Playgroud)
因为ArgumentMatcher只有一个方法,你甚至可以在Java 8中将它变为lambda:
when(client.callApi(anyString(), argThat(office -> office.id == 123L))
.thenReturn(responseOne);
Run Code Online (Sandbox Code Playgroud)
如果你已经在使用Hamcrest,你可以使用Hamcrest匹配器MockitoHamcrest.argThat,或者使用内置的hasPropertyWithValue:
when(client.callApi(
anyString(),
MockitoHamcrest.argThat(hasPropertyWithValue("id", 123L))))
.thenReturn(responseOne);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6159 次 |
| 最近记录: |