Mocking Static Methods in Mockito
July 31, 2020
Mockito has been able to mock static methods since version 3.4.0 but the documentation doesn't explain how to mock methods that take arguments.
E.g. to mock the JavaMail Transport class:
messageCaptor = ArgumentCaptor.forClass(Message.class);
try (MockedStatic<Transport> transport = mockStatic(Transport.class))
{
// mailer.send invokes Transport
mailer.send(from, to, subject, body);
transport.verify(() -> Transport.send(messageCaptor.capture()));
// Now we can see what mailer passed to Transport.send()
final Message message = messageCaptor.getValue();
}
or if we want to specify behavior:
try (MockedStatic<Transport> transport = mockStatic(Transport.class))
{
transport.when(() -> Transport.send(any(Message.class)))
.thenThrow(new MessagingException());
mailer.send(from, to, subject, body);
}