This post has been migrated to http://www.thinkcode.se/blog/2015/04/28/stubbing-a-var-arg-method-using-mockito
I had a need to stub a method the other day that had a var arg method. I failed in stubbing it using Mockito. It disturb me a lot. But after mulling on the problem a while, I searched and found a simple solution.
Mockito has a
anyVararg() method that you should use when you try to stub a method that takes a var arg as argument.
A test could look like this:
The magic is the line
when(calculator.sum((String) anyVararg())).thenReturn(expected); and specifically casting the result of
anyVararg() to a
It can be used to stub the
sum method below:
A Gradle script that can build it could be this:
I use Gradle wrapper here to ensure that I build it using Gradle 2.3.
Stubbing var arg methods is not too difficult when you know how.