How to change an object that is passed by reference to the layout in Mockito

Given the following code

@Mock Client client; ByteArrayOutputStream baos = new ByteArrayOutputStream(); client.retrieveFile(baos); // client is supposed to fill boas with data 

How can I teach Mockito how to populate a baos object?

+5
source share
2 answers

You can use Mockitos Answer .

 doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ByteArrayOutputStream baos = (ByteArrayOutputStream)args[0]; //fill baos with data return null; } }).when(client).retrieveFile(baos); 

However, if you have the opportunity to reorganize the tested code, it is better to make the client return an OutputStream or some data that can be placed in this output stream. It will be a much better design.

+4
source

try it

  doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { ByteArrayOutputStream baos = (ByteArrayOutputStream) invocation.getArguments()[0]; // fill it here return null; }}).when(client).retrieveFile(baos); 
+1
source

All Articles