java - 如何使用 Mockito 匹配二维数组参数?

标签 java testing mocking mockito powermock

我尝试模拟这个方法:

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/

相关文章:

node.js - 在从 Node 模块导出的函数上使用 `jest.spyOn`

java - 使用时区格式化日期字符串并返回日期对象

java - 模拟服务方法调用(来自内部 forEach 循环)时抛出 NullPointerException ,实现此模拟的正确方法是什么?

java - 打印同一个数组的两个重载方法?

java - Mockito 从本地方法内部模拟对象

c# - 继承抽象类并实现接口(interface)的模拟类

java - 为什么之前运行的代码中会出现错误 "Uninitialized constant DriverManager"?

java - 如果无法验证,如何检查测试用例

selenium - 如何在数据提供程序循环之外制作 @test 注释?

angular - ngx-translate 如何测试组件