Mockito检查特定对象属性值时

efl*_*lat 4 java mockito

我在工作测试中有以下内容:

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.我想我实际上不能做我正在尝试的事情,并会尝试另一种方式.当然,我愿意以其他方式表现出来.

Jef*_*ica 6

按要求重新打开,但解决方案(使用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)

  • @eflat检查你的版本.`argThat`在1.x和2.x之间变化; 在1.x Mockito的`ArgumentMatcher`中扩展了Hamcrest的`Matcher`和`Matchers.argThat`支持两者,但是他们在2.x中更好地进行版本化,而Hamcrest`argThat`变成了'MockitoHamcrest.argThat`.如果你的类路径上有两个版本,那么疯狂的事情就会发生. (3认同)