我尝试模拟这个方法:
public class Dog {
public String foo(String a, String[][] headers);
}
我想在调用 foo("hello", new String[][]{{"a", "b"}})
时返回 bar
:
Dog dog = mock(Dog.class);
when(dog.foo("hello", new String[][]{{"a", "b"}})).thenReturn("bar");
但是这不起作用,因为 Mockito 在匹配数组时使用 equals()
,并且由于它们不指向同一个对象,所以失败了:
// prints null instead of bar
System.out.println(dog.foo("hello", new String[][]{{"a", "b"}}));
请注意,被测试的代码将无法访问用作要在 #when
中匹配的参数的对象。有哪些方法可以解决这个问题?
最佳答案
尝试使用匹配器:
@Test
public void testsss() {
Dog dog = Mockito.mock(Dog.class);
Matcher<String[][]> matcher = new BaseMatcher<String[][]>() {
@Override
public boolean matches(Object item) {
return true;
}
@Override
public void describeTo(Description description) {
}
};
Mockito.when(dog.foo(Mockito.eq("hello"), Mockito.argThat(matcher))).thenReturn("bar");
Assert.assertEquals("bar", (dog.foo("hello", new String[][] { { "a", "b" } })));
}
只需实现您自己的 matches 方法而不是返回 true ;)
关于java - 如何使用 Mockito 匹配二维数组参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20675936/