views:

224

answers:

2

How do I write a unit test for a method that use an external service like System.Net.Mail?

Do I just check a return value to see if there were any errors sending the email and assume if there were none that it was sent successfully?

+6  A: 

Create a mock object for the mail service.

In short this will mean that you write a class that can replace the behavior of sending a mail. This way you can create different situations for your test very easy: a succeeded mail, a failed one, etc.

A nice and short introduction: http://www.programmersheaven.com/user/pheaven/blog/217-An-Introduction-to-Mock-Objects/

Another one, with code samples: http://blogs.clearscreen.com/ragc/archive/2004/08/31/395.aspx

Gerrie Schenck
+3  A: 

It depends on the level of testing you want. If you are more concerned with testing the method, and the emailing is just a small part, then you might consider mocking the email sending service out. Gerrie's link is good.

However, if you actually want to test the mail sending, here are some ideas.

  • Use SmtpDeliveryLocation to output the email to a folder instead of a mail server. You can then check the folder.
  • Send the email, then query the remote POP server to see if it arrived.
  • Send and assume it just worked if ther are no exceptions. I can't recall if SmtpClient.Send is blocking or non blocking.

Because these tests typically mean talking to external things, they'd be called integration tests rather than unit tests.

But in general, I think you'd be more concerned with ensuring you got the formatting/email addresses correct, than whether or not Microsoft implemented SmtpClient correctly. So unit testing and mocks make more sense there.

Paul Stovell
Agreed, it depends on what you want to test: the mail server or the business logic which is responsible in generating a mail.
Gerrie Schenck