Posts

Showing posts from July, 2017

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