Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito allow mocked return value to be set

Tags:

java

mockito

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?

like image 849
well_i Avatar asked Sep 18 '13 09:09

well_i


People also ask

Can we set values in mocked object?

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.

What does thenReturn do in Mockito?

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").

What does @mock do in Mockito?

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.

What is verify return Mockito?

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.


1 Answers

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();

like image 158
Morfic Avatar answered Sep 29 '22 15:09

Morfic