Unit testing and SMTP by ThinqLinq

Unit testing and SMTP

Over the past several years, I’ve become a fan of unit testing. I’m not a test-first/TDD zealot by any means, but have found the definite benefits of testing your custom business logic to assert that it does what you say it will. When going to a client who hasn’t done unit testing at all, I often find it hard enough to get them to start testing and don’t want to over burden their tests with mocking frameworks to abstract out some of the external dependencies. As a result, I have no qualms about incorporating both unit testing and integration testing into the mix here.

One of the things that can be tricky and time consuming to test is operations that send automatic emails via the SMTP server. If you send through a real server, the transmission can be a significant bottleneck from a performance standpoint, particularly if the server doesn’t actually exist. In the past, I’ve used local fake SMTP “servers” like the one at http://smtp4dev.codeplex.com/. With this, you simply run the server in the start tray and any time you send an email to your localhost port 25, it will show up there. In your web config, you can specify this quickly by adding the following node for your test project.

  <system.net>
    <mailSettings  >
      <smtp deliveryMethod="Network" >
        <network host="127.0.0.1" port="25" />
      </smtp>
    </mailSettings>
  </system.net>

An even better solution is to change the DeliveryMethod attribute to “SpecifiedPickupDirectory” and then specify a local path that you want new emails to appear in. From your unit test, you can then check that folder for the presence of the new email if you want to confirm that it was “sent” and open it to view the contents. The revised configuration is as follows:

  <system.net>
    <mailSettings  >
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="d:\Temp\smtp"/>
      </smtp>
    </mailSettings>
  </system.net>

One additional item I want to point out is that if you follow the MSDN help for SpecifiedPickupDirectory you will currently get a warning if you use DeliveryMethod=”specifiedPickupDirectory” with a lowercase “s”. Fortunately, VS will ignore the case on that attribute value and work either way.

Posted on - Comment
Categories: VB Dev Center) -
comments powered by Disqus