Sunday, April 17, 2011

Email Testing with Selenium

If you web application is sending some emails and if you have to test writing code that opens email client (gmail or yahoo) and then check the mails is tedious and also not reliable. The best thing you can do for this is you can have your own SMTP server, that sends the mail for you and stores any system generated mail, rather than sending to actual user for your testing. The best SMTP server I came across is Dumbster.

Now let's see how to use this
Dumster.java
public class Dumbster{
  private SimpleSmtpServer server;

     public Dumbster() {       
       if(server == null)
        server = SimpleSmtpServer.start(25);
     }

     public int howManyMainsSent() {
         int noOfMailsSent = server.getReceivedEmailSize();
         server.stop();          
         return noOfMailsSent;
     }
  
       /**
      * Use only when you are sure only 1 email has been generated
      * @return Subject of the first email
      */
    public String getEmailSubject() {
         Iterator mailIterator = server.getReceivedEmail();
         SmtpMessage email = (SmtpMessage)mailIterator.next();
         return email.getHeaderValue("Subject");
     }
  
     /**
      * Use when more then 1 email has been generated
      * @param count If more than one mails are being generated, Index of the mail
      * @return Subject of the requested email
      */
     public String getEmailSubject(int count) {
          Iterator mailIterator = server.getReceivedEmail();
          SmtpMessage email = null;
          for(int i=1; i<=count; i++){
            email = (SmtpMessage)mailIterator.next();
          }
          return email.getHeaderValue("Subject");
      }
}

Now to use Test the mail you just need to create the server of this class just before you mails shoots and then you need to call the particular function you want.

1 comments:

Abdullah said...

Hi there. I am completely new to this. I would like to check if email is being sent out after certain action in selenium. What do I need to do? Install this dumbster on my server - and what do I do at selenium? Thanks.

Post a Comment