The solutions in the question here use PowerMock. Is it possible to do this in just Mockito/JUnit?
I have a MailSender
class with a method,
sendMail(String fromAddress, String message, String toAddress);
Internally, of course, it fills in the fields to construct a MimeMessage
and uses the company's mail server to send the message.
But the last line is
javax.mail.Transport.send(mimeMessage);
I am trying to write a Junit test for the class but I do not know how to mock the Transport so that an email is not actually sent.
In MailSender, how should I modify the class to mock the call to javax.mail.Transport
?
public class MailSender {
static boolean sendMail(String fromAddress, String message, String toAddress) {
//...
MimeMessage message;
//... create the message and fill in the fields
//
transport.send(message);
}
}
For the JUnit test, I do not know what to put here. I tried this - it does not compile but I wanted to know if I am on the right track.
class MailSenderTest {
@Mock
MailSender mailSender;
@InjectMocks
Transport transport
@Test
void sendMail() {
Mockito.when(transport.sendMessage(any(), any()).thenReturn(true);
assertEquals(true, mailSender.sendMail("me@gmail.com", "hi", ""you@gmail.com"");
}