如何在 mockito 2 中匹配可变参数? [英] How match varargs in mockito 2?

查看:54
本文介绍了如何在 mockito 2 中匹配可变参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 mockito 1 的方法在更新到2.3.

Approach from mockito 1 not working after updating to 2.3.

private class ArgumentsMatcher implements ArgumentMatcher<Object[]> {
    private final Object[] expected;

    private ArgumentsMatcher(Object[] expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object[] argument) {
        return Arrays.equals(expected, argument);
    }
}

推荐答案

您可以使用这样的捕获器来匹配它:

You can match against it using a captor like this:

// Use an argument captor of whatever type the varargs method is
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verify on the method using the captor
verify(fooClass).fooMethod(captor.capture());
// Assert on the expected values
assertEquals(captor.getAllValues(), Arrays.asList("vararg1", "vararg2"));

关于这个的好处是你可以匹配数组(如果你在数组和可变参数可以混合的情况下)也可以使用你想要的任何 hamcrest 匹配器,这样你就可以做一些事情,比如验证单个元素是否存在、忽略顺序、忽略重复项或您需要执行的任何其他操作.

The nice thing about this is that you can match against arrays (if you're in a case where arrays and varargs can be mixed) also use whatever hamcrest matchers you want so you can do things like verify a single element is present, ignore order, ignore duplicates, or whatever else you need to do.

这篇关于如何在 mockito 2 中匹配可变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆