alwaysANewbie alwaysANewbie - 1 month ago 4x
Java Question

mockito partial parmaters mocking

I am trying to write unit test in java. Below is snippet of my code

class Temp {
public void method() {

return someObject.someMethod(param1, param2, param3, param4, param5);

Test Method:

public void testMethod() {

Mokito.when(someObjectMock.someMethod(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyBoolean(),
false)). thenReturn(true);

boolean status = temp.method();

Assert.assertEquals(true, status);

On executing the test case, I am however getting below error:

Invalid Use of argument matchers !
5 matchers expected, 4 recorded

If my understanding is correct, it expects all parameters passed to be mocked. However thats not what I want, I wish to mock the first 4 parameters, and based on the 5 parameter (true or false), then appropriate return value of the method will specified.

Is there way to get around this?



You need to use Matchers.eq(false) (or Mockito.eq(false), the same static methods are exposed in both places) rather than plain false for the last parameter.

That said, consider leaving all the matchers in your stubbing (when() calls) as any() rather than expecting a value. There are two cases here: either your test actually cares about what values get passed into the mock, in which case you need a verify() call (since a missed mock expectation is not an error in Mockito), or else your test doesn't care, in which case expecting a specific value just makes your test brittle. Either way, there's not any value in expecting specific arguments while stubbing unless you need to return different values from the stub based on different argument values.