axismundi
axismundi

Reputation: 111

how to change an object that is passed by reference to a mock 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 do I instruct Mockito to fill the baos object?

Upvotes: 10

Views: 6016

Answers (2)

makasprzak
makasprzak

Reputation: 5220

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 possibility to refactor the tested code, better is to make client return the OutputStream or some data that can be put to this Output stream. This is would be much better design.

Upvotes: 13

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

try this

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

Upvotes: 1

Related Questions