Normally when using mockito I will do something like
Mockito.when(myObject.myFunction(myParameter)).thenReturn(myResult);
Is it possible to do
Here's one way of doing it. This uses an Answer
object to check the value of the property.
@RunWith(MockitoJUnitRunner.class)
public class MyTestClass {
private String theProperty;
@Mock private MyClass mockObject;
@Before
public void setUp() {
when(mockObject.myMethod(anyString())).thenAnswer(
new Answer(){
@Override
public String answer(InvocationOnMock invocation){
if ("value".equals(theProperty)){
return "result";
}
else if("otherValue".equals(theProperty)) {
return "otherResult";
}
return theProperty;
}});
}
}
There's an alternative syntax, which I actually prefer, which will achieve exactly the same thing. Over to you which one of these you choose. This is just the setUp
method - the rest of the test class should be the same as above.
@Before
public void setUp() {
doAnswer(new Answer(){
@Override
public String answer(InvocationOnMock invocation){
if ("value".equals(theProperty)){
return "result";
}
else if("otherValue".equals(theProperty)) {
return "otherResult";
}
return theProperty;
}}).when(mockObject).myMethod(anyString());
}