Over a million developers have joined DZone.

Email 101 Unit Tests

// Two unit tests for my Email 101 code. The first expects connection information to
// be in the System properties. That can be setup as part of running the unit tests
// from either Ant or Eclipse. Note: The first test only confirms that the send occurs
// without error, not that the email was actually received or received at the correct
// address.
// The second test trashes the SMTP server name and then confirms that it results in
// an exception being thrown from the mail sending code.

package com.johnmunsch.util;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import junit.framework.TestCase;

public class MailTest extends TestCase {
    String from = null;
    String to = null;
    String title = null;
    String textBody = null;
    String htmlBody = null;
    String smtpServer = null;
    /* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
    protected void setUp() throws Exception {
        from = System.getProperty("from");
        to = System.getProperty("to");
        title = System.getProperty("title");
        textBody = System.getProperty("textBody");
        htmlBody = System.getProperty("htmlBody");
        smtpServer = System.getProperty("smtpServer");

     * This is a terrible test. It could fail just as easily because it is 
     * incorrectly supplied with parameters as due to any failure in the code.
     * @throws MessagingException 
     * @throws AddressException 
    public void testSendMail() throws AddressException, MessagingException {
        Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
     * Same test as above except that we screw up the smtpServer address so it
     * is absolute garbage. In that case we should see a failure, which we are
     * looking for, and we throw an error if we _don't_ see some kind of
     * exception.
    public void testSendMailWithBadServer() {
        smtpServer = "garbageingarbageout";
        try {
            Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
        } catch (AddressException e) {
            // Exception good, no exception bad.
        } catch (MessagingException e) {
            // Exception good, no exception bad.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}