Can Mockito mock a method without specifying each argument matcher individually?

huangapple 未分类评论41阅读模式
英文:

Can Mockito mock a method without specifying each argument matcher individually?

问题

让我们假设我有一个带有5个参数的方法,如下所示:

public int foo(int arg1, int arg2, int arg3, int arg4, int arg5) {
  //do something
}

当我进行模拟时,最终我会做类似于以下的操作:

Mockito.when(myClass.foo(anyInt(), anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(expectedResult);
//做一些操作
Mockito.verify(myClass).foo(expectedArg1, expectedArg2, expectedArg3, expectedArg4, expectedArg5);

是否有一种方法可以将所有的 anyInt() 匹配器组合成更易读的形式?类似于 Collections.nCopies(5, anyInt()); 这样的方式?

英文:

Let's say I have some method with 5 arguments, like

public int foo(int arg1, int arg2, int arg3, int arg4, int arg5) {
  //do something
}

When I mock it, I end up doing something to the effect of

Mockito.when(myClass.foo(anyInt(), anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(expectedResult);
//do stuff
Mockito.verify(myClass).foo(expectedArg1, expectedArg2, expectedArg3, expectedArg4, expectedArg5);

Is there a way of combining all the anyInt() matchers into something that's easier on the eyes? Something like Collections.nCopies(5, anyInt());

答案1

得分: 0

这将始终更好地重构你的foo方法的参数。使用包含所有参数的包装器,不仅会在测试部分使其更易读,而且还将使你的类结构更清晰。关于你的请求,由于你正在使用myClass.foo(...)方法,所以不可能,因为你必须逐个指定参数。

英文:

It will always better refactoring your foo method's arguments. Use wrapper which contains all arguments it will not only make it easier on eyes in the testing section and also it will make your class structure clear. Regarding your request, it is not possible because you are using myClass.foo(...) method you have to specify arguments one by one.

huangapple
  • 本文由 发表于 2020年7月25日 04:15:15
  • 转载请务必保留本文链接:https://java.coder-hub.com/63080847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定