I want to mock a class which has a varargs parameter method. Based on is there Mockito eq matcher for varargs array? I came up with the following but the ArgumentMatcher is not called at all.
My class to mock:
public class ProcessUtil {
public Result execute(String... commandParts) throws Exception { ... }
}
My class to test (InstallService
) executes a couple of ProcessUtil.execute()
and I want to return different Results based on the varargs of the call. Therefor I created this ArgumentMatcher:
class StringVarArgsMatcher implements ArgumentMatcher<String[]>,VarargMatcher {
private String[] expectedValues;
StringVarArgsMatcher(String... expectedValues) {
this.expectedValues = expectedValues;
}
@Override
public boolean matches(String[] arguments) {
boolean matched = false;
for(int i = 0; i < expectedValues.length; i++) {
matched = "".equals(expectedValues[i]) || arguments[i].endsWith(expectedValues[i]);
}
return matched;
}
}
My test is constructed this way:
@Test
public void test() throws Exception{
ProcessUtil processUtilMock = mock(ProcessUtil.class);
ProcessUtil.Result installCommandResult = new ProcessUtil.Result(Collections.emptyList(), Collections.emptyList());
when(processUtilMock.execute(argThat(new StringVarArgsMatcher(new String[]{"", "", "", "", "--install"})))).thenReturn(installCommandResult);
InstallService installService = new InstallService(processUtilMock);
boolean databaseInstalled = installService.installDatabase();
Assert.assertFalse(databaseInstalled);
}
When I run my test it seems that the ArgumentMatcher is not called at all. If I set any breakpoint inside of the matcher execution will not stop. My InstallService
will also get a NullPointer-Exception when it tries to evaluate the Result of ProcessUtil.execute()
What is it that I am missing?