Filed under: Java, Mockito, Programming, TDD, — Tags: Mocking, stub var arg, stubbing, var arg — Thomas Sundberg — 2015-04-28
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:
src/test/java/se/thinkcode/CalculatorTest.java
package se.thinkcode;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
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:
src/main/java/se/thinkcode/Calculator.java
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:
build.gradle
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.