Reputation: 1023
mockito masters, I have a challenge for you! ;)
I have a method that takes no arguments and I would like to mock its behaviour as to provide different results, depending on external conditions.
For instance, I'd like to do something like this:
MyInterface myMock = mock(MyInterface.class);
Sky sky = buildRandomSkyColor();
when(myMock.methodWithNoArguments()).thenReturn("blue").if(sky.isBlue());
when(myMock.methodWithNoArguments()).thenReturn("grey").if(sky.isGrey());
Is it possible to have this conditional kind of behaviour on Mockito? I've also tried using doStub()
and doAnswer()
, but got nowhere.
Any help is greatly appreciated! Thanks a lot!
Upvotes: 4
Views: 4948
Reputation: 8519
You could use a custom answer to do this
MyInterface myMock = mock(MyInterface.class);
Sky sky = buildRandomSkyColor();
when(myMock.methodWithNoArguments()).thenAnswer(new Answer<String>(){
String answer(InvocationOnMock invocation) {
if(sky.isBlue())
return "blue";
else
return "gray";
}
}
Upvotes: 12