Miyagi Coder
Miyagi Coder

Reputation: 5532

Unit Testing my Email Service

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?

Upvotes: 2

Views: 734

Answers (2)

Paul Stovell
Paul Stovell

Reputation: 32725

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.

Upvotes: 4

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

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

Upvotes: 7

Related Questions