Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 305
axismundi Avatar asked Apr 15 '15 07:04

axismundi


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

like image 143
macias Avatar answered Nov 12 '22 13:11

macias


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);
like image 1
Evgeniy Dorofeev Avatar answered Nov 12 '22 11:11

Evgeniy Dorofeev