jeudi 13 juin 2019

Test if the mail sent sucessfully using Java

I have a mailingService who sends the mail:

@Component
public class MailingServiceImpl implements MailingService{

    @Autowired
    JavaMailSenderImpl mailSender;

    @Override
    public void sendMail(String sender, String receiver, String subject, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(receiver);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
}

and I'm writing a test for this void sendMail(...) and I need to check if the mail was sent successfully. I found GreenMail that Im currently trying to use for my test, here is the code:

public class MailingServiceImplTest {

    private MailingServiceImpl mailingServiceImpl;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @PostConstruct
    public void testConnection() {
        try {
            mailSender.testConnection();
        } catch(MessagingException ex) {
            throw new IllegalStateException("[Warning] Mail server is not available. " + ex);
        }
    }

    @Rule
    public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP);

    @Test
    public void testSendMail() throws IOException {
        GreenMailUtil.sendTextEmailTest(receiver, sender, subject, content);
        // GreenMailUtil.sendTextEmailTest(to, from, subject, body);  -- here I could use the GreenMailUtil sendTextEmailTest, but I need to use my void sendMail function
        MimeMessage[] emails = greenMail.getReceivedMessages();
//      assertEquals(1, emails.length);
    }

Any ideas how to test my method? GreenMail (like example 'Using JUint (rule based setup)' section) isn't the only tool I tried, tried Dumbster (like example below, but sendMessage requires the strings as parameters, I can't pass my method. am I doing something wrong? Help

Aucun commentaire:

Enregistrer un commentaire