Friday, October 28, 2005

Testing Email Components

I always made sure I write tests before writing a method in an object.This gives me a clear idea what this method has to do.In my current project, I needed a method that sends a email. I was not sure how to write a test for this method. Then Pat Gremo ( another ThoughtWorker ) told me to check out the Dumbster (http://sourceforge.net/projects/dumbster) , a simple SMTP server that we could use in our automated Test suites.It was so simple to incorporate in my JUnits.
This is how I incorporated Dumbster in my Junit.

Method to Test:-
public void sendMessage(String hostName,
String portNo,
String addrFrom,
String nameFrom,
String addrTo,
String nameTo,
String subject,
String message) ;

JUnit:-
import java.util.Iterator;
import junit.framework.TestCase;
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SmtpMessage;

public class EmailTest extends TestCase{

public void testSendMessage() {

EmailSender emailSender = new EmailSender();

//Starting the Dumbster's SMTP Default Server. It listens to port No 25
SimpleSmtpServer server = SimpleSmtpServer.start();

//Sending the message
email.sendMessage("localhost",
"25",
"siva@junit.com",
"tester",
"Siva@nowhere.com",
"Siva",
"Test Email",
"I am glad u got it");

//Stopping the SMTPDefault Server
server.stop();

//Checking no of emails received my the SMTPServer
assertTrue(server.getReceievedEmailSize() == 1);

//Getting all the emails recivied by SMTP Server as an Iterator
Iterator emailIter = server.getReceivedEmail();
SmtpMessage email = (SmtpMessage)emailIter.next();

//Checking the Subject of the email
assertTrue(email.getHeaderValue("Subject").equals("Test Email"));

//Checking the To Address of the email
assertTrue(email.getHeaderValue("To").equals("Siva "));

//Checking the From Address of the email
assertTrue(email.getHeaderValue("From" ).equals("tester "));

//Checking the Message of the email
assertTrue(email.getBody().equals("I am glad u got it"));

}

}


For information on Dumbster check out these sites,
http://sourceforge.net/projects/dumbster
http://www.javaworld.com/javaworld/jw-08-2003/jw-0829-smtp.html

2 comments:

Dave Nicolette said...

There's another tool, very similar, called smtpunit. See the sourceforge page.

Siva Jagadeesan said...

Thanx Dave

I will look at that too