MaximeFrancoeur of TwinsLabs
4/28/2015 - 12:40 PM

Complex Stubbing with Mockito for Java

Complex Stubbing with Mockito for Java

@Mock private SmtpConnection smtpConnection;
 
private void mockSmtpConnection() {
    final ArgumentCaptor<String> recipient = ArgumentCaptor.forClass(String.class);
    final ArgumentCaptor<String> subject = ArgumentCaptor.forClass(String.class);
    final ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
 
    when(smtpConnection.setRecipient(recipient.capture()))
        .thenReturn(smtpConnection);
    when(smtpConnection.setSubject(subject.capture()))
        .thenReturn(smtpConnection);
    when(smtpConnection.setMessage(body.capture()))
        .thenReturn(smtpConnection);
 
    when(smtpConnection.getOutgoingClientData())
        .thenAnswer(new Answer<String> {
        @Override
        public String answer(InvocationOnMock call) {
            return recipient.getValue() + "\0"
                + subject.getValue() + "\0"
                + body.getValue();
        }
    });
}