如何正确匹配Mockito中的varargs [英] How to properly match varargs in Mockito

查看:247
本文介绍了如何正确匹配Mockito中的varargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图使用Mockito来模拟一个使用vararg参数的方法:

I've been trying to get to mock a method with vararg parameters using Mockito:

interface A {
  B b(int x, int y, C... c);
}

A a = mock(A.class);
B b = mock(B.class);

when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b);
assertEquals(b, a.b(1, 2));

这不起作用,但如果我改为:

This doesn't work, however if I do this instead:

when(a.b(anyInt(), anyInt())).thenReturn(b);
assertEquals(b, a.b(1, 2));

尽管在删除方法时我已完全省略了varargs参数,但这仍有效。

This works, despite that I have completely omitted the varargs argument when stubbing the method.

任何线索?

推荐答案

Mockito 1.8.1推出 anyVararg()匹配器

Mockito 1.8.1 introduced anyVararg() matcher:

when(a.b(anyInt(), anyInt(), Matchers.<String>anyVararg())).thenReturn(b);

另见历史记录: https://code.google.com/archive/p/mockito/issues/62

编辑新语法:

when(a.b(anyInt(), anyInt(), ArgumentMatchers.<String>any())).thenReturn(b);

这篇关于如何正确匹配Mockito中的varargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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