Stubbing method which manipulates parameters using Mockito
Mockito is a mocking framework which enables mock creation, verification and stubbing. It has been widely used in Java community to write beautiful tests with its clean and simple API.
Recently I was writing a unit test which involves stubbing a non-void method that manipulates the given parameter.
The method would look like this:
public interface Accessor {
Data get(String dataId, Attribute attribute);
}
The get method will return the data associated with the given id and set the attribute of data accordingly.
We can create the mock as usual:
Accessor accessor = Mockito.mock(Accessor.class);
Following code snippet shows how to manipulate the parameter in get method:
Mockito.when(accessor.get(anyString(), any(Attribute.class))).thenAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
Object[] args = invocationOnMock.getArguments();
Attribute attribute = (Attribute) args[1];
// Set the attribute
attribute.setVersion(2017);
Data data = new Data();
// Set the value of data as you need
...
return data;
}
});
We need the Answer which is a generic interface to configure the mock's answer. Because the get method is not void method we can not used the API doAnswer.
On the other hand, the get method manipulates the given parameter attribute, we can not use the API thenReturn either.
So we have to use thenAnswer and override the answer method to specify the action that is executed and the return value that is returned when you interact with the mock.
We know the second parameter is the one the get method manipulates so we can cast it to Attribute and set it as needed. Also the get method returns the data we need to prepare its value accordingly.
Summary
- Use thenAnswer when you want to stub a non-void method with generic Answer to specify the action that is executed and the return value.
- Use doAnswer when you want to stub a void method method with generic Answer to specify the action that is executed.
- Use thenReturn when you want to stub a non-void method and set consecutive return values to be returned when the method is called.
References
- Mockito documentation. Retrieved 29 July 2017.
Comments
Post a Comment