Is it possible to change the value that is returned from a mocked object?
Below is an example that explains what I am trying to do.
public class MyClass{
public void method(Mock obj){
if(obj.getValue.equals("value"){
obj.setValue("changedValue");
}
anotherObj.call(obj.getValue());
}
So the above class is very simplified. It will change the value returned if the value passed in equals value.
@Test
public void test(){
Mock obj = mock(Mock.class);
when(obj.getValue()).thenReturn("value");
testClass.method(obj);
verify(anotherObj, times(1)).call("changedValue");
}
The test want to verify that the anotherObj.call is called with the changed value, but since we have mocked the return value to be 'value' this will fail as 'value' is returned.
Is it possible to create a test using a mocked returnValue?
You can set the mock object property to the value returned by the mock object method. To achieve this, specify separate behaviors for the method and the property. You can specify one behavior at a time.
thenReturn or doReturn() are used to specify a value to be returned upon method invocation. //”do something when this mock's method is called with the following arguments” doReturn("a").
Mockito @Mock Annotation We can mock an object using @Mock annotation too. It's useful when we want to use the mocked object at multiple places because we avoid calling mock() method multiple times. The code becomes more readable and we can specify mock object name that will be useful in case of errors.
Mockito verify() methods can be used to make sure the mock object methods are being called. If any method call is deleted by mistake, then verify method will throw an error.
Johnatan is right. If obj
is not a complex object, you can avoid mocking it and use a real one.
If for some reason this is not possible, mockito allows to define a series of answers, eg: when(obj.getValue()).thenReturn("value").thenReturn("modifiedValue");
which could be what you are looking for.
Although it might be overkill, just to make sure that all was ok, I would also verify(obj).setValue("changedValue");
and verify(obj, times(2)).getValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With