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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With