Thomas Sundberg

April 28, 2015

Stubbing a var arg method using Mockito

Filed under: Gradle, Java, Mockito, Programming, TDD — Tags: , , , , , , , — Thomas Sundberg @ 23:28

This post has been migrated to

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:


package se.thinkcode; import org.junit.Test; import static; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyVararg; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CalculatorTest { @Test public void mock_string_var_arg_method() { int expected = 17; Calculator calculator = mock(Calculator.class); when(calculator.sum((String[]) anyVararg())).thenReturn(expected); int actual = calculator.sum(); assertThat(actual, is(expected)); } }

The magic is the line when(calculator.sum((String[]) anyVararg())).thenReturn(expected); and specifically casting the result of anyVararg() to a String[].

It can be used to stub the sum method below:


package se.thinkcode; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class Calculator { public int sum(String... args) { throw new NotImplementedException(); } }

A Gradle script that can build it could be this:


plugins { id 'java' } dependencies { testCompile "junit:junit:4.12" testCompile "org.mockito:mockito-all:1.10.19" } repositories { jcenter() } task wrapper(type:Wrapper) { gradleVersion = '2.3' }

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.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: