这听起来像是一个非常简单的问题,但我真的很难归档解决方案。
通常我很容易模拟并匹配我的论点。
现在我正在匹配这样的方法:
getAppFacebookClient(page, V2_11).publish(destination, JsonObject.class, parameters.asArray());
这是一个 Facebook 应用程序,参数是自定义对象的列表。 asArray[] 方法是在类中创建的,基本上执行如下操作:
public Parameter[] asArray() {
return parameters.toArray(new Parameter[parameters.size()]);
}
并且此返回的参数的类型为com.restfb.Parameter
所以,我基本上就是这样做的
when(client.publish(anyString(), eq(JsonObject.class), any(com.restfb.Parameter[].class))).thenReturn(result)
;
但似乎从未被采用,当然我无法操纵结果,
知道如何以正确的方式模拟这种对象吗?
我也尝试过其他方法
doReturn(result).when(client).publish(anyString(), eq(JsonObject.class), any(com.restfb.Parameter[].class));
最佳答案
您的代码是正确的...除非发布
使用可变参数!
在这种情况下,您需要使用 any()
/anyVararg()
匹配器。
考虑:
@Mock Thingy testee;
interface Thingy {
int f(String... arg);
}
@Test
public void test() {
// given
// works only if signature is `f(String[] arg)`
// when(this.testee.f(Mockito.any(String[].class))).thenReturn(42);
when(this.testee.f(Mockito.any())).thenReturn(42); // anyVararg() is deprecated
// when
final int result = this.testee.f(new String[] { "hello", "world" });
// then
assertThat(result, comparesEqualTo(42));
// works only if signature is `f(String[] arg)`
// verify(this.testee).f(Mockito.any(String[].class));
verify(this.testee).f(Mockito.any());
}
关于java - 如何用mockito拦截普通对象数组的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287408/