DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Email 101 Unit Tests

02.27.2006
| 8108 views |
  • submit to reddit
        // 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);
            
            fail();
        } catch (AddressException e) {
            // Exception good, no exception bad.
        } catch (MessagingException e) {
            // Exception good, no exception bad.
        }
    }
}