Subscribe Now

ABC, 123, Ruby, C#, SAS, SQL, TDD, VB.NET, XYZ

Thursday, November 8, 2007

Unit Testing an Email Method


I recently ran into the problem of needing to unit test a web method in an app that sends email. Searching the web, I finally found this which helped me develop my test. Many thanks to Simon Soanes for his post. Here’s the C# 2.0 test harness code.

using System;
using NUnit.Framework;
using MyApp.WebLayer;
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook; //Refs Microsoft Outlook 11.0 Object Library

namespace TestHarness
public class EmailServiceTestSuite
public void SendRegularText()
EmailWebService.EmailService svc = new EmailWebService.EmailService();
DateTime now = DateTime.Now;
svc.SendRegularText("", "SendRegularText Test Email - " + now, "");

System.Threading.Thread.Sleep(10000); //Wait 10 seconds for email to arrive...sometimes not enough

Outlook.ApplicationClass outlookApp = null;
Outlook.NameSpace outlookNS = null;
bool emailArrived = false;
outlookApp = new Outlook.ApplicationClass();
outlookNS = outlookApp.GetNamespace("MAPI");
outlookNS.Session.Logon("outlook", "", false, true);
Outlook.MAPIFolder inbox = outlookNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
foreach (Outlook.MailItem email in inbox.Items)
if (email.Subject == "SendRegularText Test Email - " + now)
emailArrived = true;
if (outlookNS != null)
Assert.IsTrue(emailArrived, "Email failed to arrive");

For testing purposes, I just send a test email to myself with a guaranteed unique subject line, wait for 10 seconds which is usually enough time for the email to show up in my Outlook Inbox, then assert that the email is present. The SendRegularText web method accepts three parameters: email recipient, subject line, and body text (left blank in the test).

1 comment: