Reputation: 36654
I'm using a mockito mock.
I want to control the invocation of method foo(String a, Date b)
to call the original method with foo(a, fixed_date)
How can I use mockito API to do so?
MyObject myObject = mock(MyObject.class);
when(myObject.foo(anyString, any(Date.class))
.thenCallRealMethod();
why this doesn't work?
It never redirects the call
ImagesSorter imagesSorter = spy(new ImagesSorter());
doReturn(imagesSorter.sortImages(images, user, fakeNowDate)).when(imagesSorter).sortImages(images,user);
Upvotes: 3
Views: 1854
Reputation: 1846
I have a solution, but it's a little hacky, let's assume the return type for foo
is String
:
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
...
final Date fixedDate = ...;
MyClass myObject = mock(MyClass.class);
when(myObject.foo(anyString(), any(Date.class))).thenAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
// Switch the 2nd argument
invocation.getArguments()[1] = fixedDate;
// Then call the real method
return (String) invocation.callRealMethod();
}
});
With MyClass
being for example:
public class MyClass {
public String foo(String s, Date d) {
return s + d;
}
}
EDIT:
In your last example with ImageSorter
, i think you don't need Mockito, a simple decorator would do the trick:
public interface ImageSorter {
void sortImages(Images images, User user);
void sortImages(Images images, User user, Date date);
}
public class ImageSorterDecorator implements ImageSorter {
final ImageSorter delegate;
final Date fixedDate;
public ImageSorterDecorator (ImageSorter delegate, Date fixedDate){
this.delegate = delegate;
this.fixedDate = fixedDate;
}
public void sortImages(Images images, User user){
delegate.sortImages(images, user, fixedDate);
}
public void sortImages(Images images, User user, Date date){
delegate.sortImages(images, user, fixedDate);
}
}
Upvotes: 2