grd
grd

Reputation: 45

Passing actual arguments in mockito stubbing

For a case in which stubbed variable in made inside the actual production code, How can we pass actual arguments with stubbing e.g using Mockito.when in JUnits?

E.g if a method in production code is like:

1) servicaClass.doSomething(Calendar.getInstance)

2) servicaClass.doSomething(someMethodToCreateActualVariable())

while testing how a actual parameter can be passed? Like

-> when(mockedServiceClass.doSomething(Calendar.geInstance)).thenReturn("")

But while testing production code will take its own calendar value while executing.

There can be a way to make public setter getter method for the used variable to be stuffed. But that dont seem to be a optimum solution.

Any pointers with this regard will be helpful?

Upvotes: 1

Views: 2800

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95614

If you know the matching value before the fact, you can use stubbing. Mockito matchers like eq (compare with equals) and same (compare with ==) will help there, or you can get the eq behavior by specifying the value directly. Note that you have to use Matchers for all values if you use any at all; you can't use Matchers for only one argument of a two-argument method call.

// Without matchers
when(yourMock.method(objectToBeComparedWithEquals))
    .thenReturn(returnValue);

// With matchers
when(yourMock.method(eq(objectToBeComparedWithEquals)))
    .thenReturn(returnValue);
when(yourMock.method(same(objectToBeComparedReferentially)))
    .thenReturn(returnValue);

If you don't know the matching value until after you run the method, you might want verification instead. Same rules apply about Matchers.

SomeValue someValue = yourSystemUnderTest.action();
verify(yourMock).initializeValue(someValue);

And if you need to inspect the value after the fact, you can use a Captor:

ArgumentCaptor myCaptor = ArgumentCaptor.forClass(SomeValue.class);
yourSystemUnderTest.action();
verify(yourMock).initializeValue(myCaptor.capture());
SomeValue valueMockWasCalledWith = myCaptor.getValue();

// Now you've retrieved the reference out of the mock, so you can assert as usual.
assertEquals(42, valueMockWasCalledWith.getInteger());

Upvotes: 1

Related Questions