Thursday, December 18, 2008

Preconditions, Postconditions, Invariants : Design by Contract for Java #2

Recently I wrote about how to apply "Design by Contract" with Java. I proposed to use the assert statement of java, in case you do not want to set up some external tools like Contract4J, iContract or Jass. After using the assert statement for a while I would recommend to use your own implementation of assertions instead like this:
public class Assertion {

 /**
  * Precondition.
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Require(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Precondition: The expectation '" + description + "' is violated");
     }
 }

 /**
  * Precondition.
  * @param objectToBeTested is an object we expect to be not null
  * @param objectName is the name of the variable we test.
  */
 public static void RequireNotNull(Object objectToBeTested,String objectName) {
     if (objectToBeTested == null) {
         throw new RuntimeException("Precondition: The expectation '" + objectName + " is not null' is violated");
     }
 }

 /**
  * Postcondition.
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Ensure(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Postcondition: The expectation '" + description + "' is violated");
     }
 }

 /**
  * Common condition to be used in the middle of methods
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Check(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Condition: The expectation '" + description + "' is violated");
     }
 }
}
Why is the own implementation better than the assert statement?
  1. It does not make sense to switch off the runtime checks of assertions. We use assertions to simplify and avoid the error handling code in our methods. When it is possible to switch of assertions we loose this advantage, because we have to prepare our code to handle situations where the assertions are not checked.
  2. We are not only profiting from assertions during development and testing but also when the software is deployed. Assertions uncover error conditions much clearer and with better error descriptions. The logs in a production system will contain the messages from assertions and will help to find the cause of the problem much faster. If we switch off the assertions the problems will occurring much later and the cause of the problem can only be found with much more effort,
You can find details about "Design by Contract" in the famous book Object-Oriented Software Construction by Bertrand Meyer.

Monday, December 15, 2008

Mocking an object with two interfaces

Currently I spend a lot of time with maintaining 'legacy' java code. That is not really funny :-(. To make the most out of it, I write as much unit tests as possible to gain some more confidence in the code and be prepared for future bugfixes and refactorings. I stumbled over a small problem, when I tried to mock an object which implements two interfaces. My 'system under test'(SUT) class TextManager uses an object which is an IReader and an IWriter at the same time. The object is only handed over once and the TextManager has to cast the IReader object into an IWriter object. The whole design is not really outstanding (to be polite) and I would have implemented it myself a little bit different.
public class TextManager {
   
   private IReader reader;
   
   public void readAndWrite() {
      String text = reader.read();
      text = "*" + text + "*";
      ((IWriter)reader).write(text);
   }
}
I wrote a unit test for the readAndWrite() method and recognized that I can't simply create a jMock object for the IReader/IWriter object. My colleague Henning found a simple an effective solution. In my test package I create a new interface called IReaderWriter which extends IReader and IWriter. Now I can create a mock object for this new interface which is able to work as a test double inside TextManager:
public void testReadAndWrite() {
    
    // Setup
    final IReaderWriter mock = context.mock(IReaderWriter.class);
    TextManager textManager = new TextManager(mock);
    context.checking(new Expectations() {{
        one(mock).read(); will(returnValue("test"));
        one(mock).write("*test*");
    }});
    
    // Exercise
    textManager.readAndWrite();
    
    // Verify
    context.assertIsSatisfied();
}

Thursday, November 27, 2008

Preconditions, Postconditions, Invariants : Design by Contract for Java

In his famous book Object-Oriented Software Construction Bertrand Meyer described a design technique called "Design by Contract" (DBC) which can improve software quality dramatically. His programming language Eiffel supports this design technique inherently. This valuable technique is universal and widely accepted and can be used regardless in which programming language you are developing. To apply this technique in Java you need to define and execute assertions at runtime. The pre-, and postconditions of a method should also be part of the javadoc documentation.

There are a lot of tools and framework which help you to apply DBC to your Java code. For example OVal, Contract4J, which are using AspectJ, iContract or Jass, which are using a preprocessor for Java.

In some circumstances it might be too much effort to apply one of these tools to you development project. Luckily there was a rudimentary support for testing assertions added to the Java language starting with release 1.4. The assert statement allows to define runtime checks inside your code. With some simple conventions you can benefit from DBC without heavy tool support. Here is an example how to use the assertion mechanism of Java to apply "Design by Contract":

/**
* Is the editor in the edit mode?
* @return True, if the editor is in the edit mode. Otherwise false.
*/
public boolean isInEditMode() {
 ...
}

/**
* Sets a new text.
* Precondition: isEditMode()
* Precondition: text != null
* Postcondition: getText() == text
* @param name
*/
public void setText(String text) {
 assert isInEditMode() : "Precondition: isInEditMode()";
 assert text != null : "Precondition: text != null";

 this.text = text;

 assert getText() == text : "Postcondition: getText() == text";
}


/**
* Delivers the text.
* Precondition: isEditMode()
* Postcondition: result != null
* @return
*/
public String getText() {

 assert isInEditMode() : "Precondition: isInEditMode()";

 String result = text;

 assert result != null : "Postcondition: result != null";
 return result;
}

So you can use "Design by Contract" effectively with three simple rules:

  • Use the assert mechanism of Java to check preconditions, postconditions and invariants at runtime.
  • Describe each assert with a string that starts either with "Precondition:", "Postcondition:" or "Invariant:" followed by the textual description of the assert expression.
  • Add each assert description string to the javadoc comment of the method
We can get a little more support, when we write our own pre- and postcondition class:
public class Assertion {

   /**
    * Precondition.
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Require(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Precondition: The expectation '" + description + "' is violated");
       }
   }
  
   /**
    * Precondition.
    * @param objectToBeTested is an object we expect to be not null
    * @param objectName is the name of the variable we test.
    */
   public static void RequireNotNull(Object objectToBeTested,String objectName) {
       if (objectToBeTested == null) {
           throw new RuntimeException("Precondition: The expectation '" + objectName + " is not null' is violated");
       }
   }

   /**
    * Postcondition.
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Ensure(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Postcondition: The expectation '" + description + "' is violated");
       }
   }

   /**
    * Common condition to be used in the middle of methods
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Check(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Condition: The expectation '" + description + "' is violated");
       }
   }
}
Using this class instead of 'assert' has the advantage that we can't forget to switch on the runtime checking of the assertions with -enableassertions. But keep in mind you still have to add method comments for the assertions. This is important, because the assertions should help the users of your class without forcing them to read your implementation details:
/**
* Sets a new text.
* Require: isEditMode()
* Require: text != null
* Ensure: getText() == text
* @param name
*/
public void setText(String text) {
 Assertion.Require(isInEditMode(),"isInEditMode()");
 Assertion.RequireNotNull(text, "text");

 this.text = text;

 Assertion.Ensure(getText() == text,"getText() == text");
}


/**
* Delivers the text.
* Require: isEditMode()
* Ensure: result != null
* @return
*/
public String getText() {

 Assertion.Require(isInEditMode(),"isInEditMode()");

 String result = text;

 Assertion.Ensure( result != null, "result != null";
 return result;
}

There is also an article "Using Assertions in Java Technology" on the Sun Developer network. See "Preconditions, Postconditions, Invariants : Design by Contract for Java #2" for further infos.

Tuesday, October 28, 2008

CruiseControl, ClearCase and Dynamic Views

When I set up CruiseControl in our development infrastructure, I struggled a little bit with the ClearCase integration. I got a lot of information from the very good book Kevin A. Lee: IBM Rational(R) ClearCase(R), Ant, and CruiseControl: The Java(TM) Developer's Guide to Accelerating and Automating the Build Process. Unfortunately the book is not explicit whether to use dynamic or snapshot views in conjunction with CruiseControl. In our project most of the developers are using dynamic views to set up their private workspaces. So I tried to use dynamic views as well for CruiseControl. That was not a brilliant idea. Whats the problem? When I set up CruiseControl as a windows service, I put the CruiseControl configuration file 'config.xml' into ClearCase. I recognized that the dynamic view with the 'config.xml' is not accessible by the service. Dynamic views have to be started with a cleartool command and then are mapped as drives. That must happen before the windows service is started. That seems not an straight forward solution when you are using the Java Service Wrapper. Also mapped drives are not accessible by a windows service as long as no user is logged on. You can't use the drive letter, instead you have to use an URL. In the end it was much easier to set up CruiseControl with a snapshot view.

Tuesday, August 26, 2008

TDD and Layered Architecture

I just read the blog post of Jeffrey Palermo about the Onion Architecture (see also the similar pattern Hexagonal architecture). Aspects of this patterns are used in an architecture our team defined for a healthcare information system.

Interesting is Jeffrey's rationale for moving certain components to the outer layer: The "infrastructure is pushed out to the edges where no business logic code couples to it", because "this code is most likely to change frequently as the application goes through years of maintenance". I think this is absolutely true.

Eric Evans presented a pattern called Layered Architecture in his book Domain-Driven Design: Tackling Complexity in the Heart of Software. His rationale for for moving certain components to the outer layer: The domain model should be separated from the technical details so it contains only the concepts we want to discuss with the domain experts. That is also a very good guideline when we have decide in which layer a certain piece of code belongs.

A third rational for moving certain components to the outer layer we get when we are using TDD: All components which can't be tested by pure unit tests should be placed on the outer layer. These components should be as thin as possible, because we want to test as much code as possible by pure unit tests. Components which do not have an API defined in the implementation language like GUI components, Windows Services, Wrapper to other languages and platforms and so on are candidates for the outer layer. Here we can't use pure unit tests. Slower or more awkward tests type have to be used. Data access components for databases contain or generate SQL statements. These data access components should be tested in conjunction with the real database to verify the correctness of the SQL statements. I call these tests database unit tests. They are much slower than the pure unit tests.

Friday, July 25, 2008

Configure CruiseControl Logging

If you have problems to get your CruiseControl running you may want to see some more log output. For example when your < modificationset> configuration does not work as expected, you want to see which commands are submitted for retrieveing the modifications in your source code repository. To switch on more log output create a log4j.properties file and place it in the CruiseControl folder side by side with the CruiseControl.bat and the config.xml file. The file may contain a log4j configuration like:
# Set root logger level to ERROR (default)
log4j.rootLogger=ERROR, CONSOLE, FILE
log4j.logger.net.sourceforge.cruisecontrol=INFO
log4j.logger.net.sourceforge.cruisecontrol.sourcecontrols=DEBUG

# A1 is to console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%-9t] %-5p %-14.14c{1}- %m%n

# FILE is file logger with rotation
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d [%-9t] %-5p %-14.14c{1}- %m%n
log4j.appender.FILE.File=cruisecontrol.log
log4j.appender.FILE.MaxFileSize=5000KB
log4j.appender.FILE.MaxBackupIndex=4
Modify the CruiseControl.bat which starts the CruiseControl build loop. Add the command line parameter "-Dlog4j.configuration=file:./log4j.properties" to the call of the java application:
set CCDIR=%~dp0

:checkJava
if not defined JAVA_HOME goto noJavaHome
set JAVA_PATH="%JAVA_HOME%\bin\java"
set CRUISE_PATH=%JAVA_HOME%\lib\tools.jar
goto setCruise

:noJavaHome
echo WARNING: You have not set the JAVA_HOME environment variable. Any tasks relying on the tools.jar file (such as "< javac>") will not work properly.
set JAVA_PATH=java

:setCruise
set LIBDIR=%CCDIR%lib

set LAUNCHER=%LIBDIR%\cruisecontrol-launcher.jar

set EXEC=%JAVA_PATH% %CC_OPTS% -Djavax.management.builder.initial=mx4j.server.MX4JMBeanServerBuilder -Dlog4j.configuration=file:./log4j.properties -jar "%LAUNCHER%" %* -jmxport 8001 -webport 8080 -rmiport 1099
echo %EXEC%
%EXEC%
With this setup you get more detailed output concerning the access towards the source code repository.

Thursday, May 22, 2008

A New xUnit Test Pattern

Inspired by the Gerard Meszaros book xUnit Test Patterns: Refactoring Test Code, I have written down a pattern, which I used already many times:

Own Library Interface

Also known as: 'Skin and Wrap the API' [Working Effectively with Legacy Codeby Michael Feathers]

How can we make a code testable, when the code depends on a library class, which can't be replaced by a 'Test Double'?

We write our own interface that exactly mirrors the API of the library class. In our system under test (SUT) we use the interface instead of the library class itself.

The code we want to test is the system under test (SUT). It references a depended-on component (DOC) library class.

Some library classes do not inherit from an interface, they do not declare their methods as virtual or they provide static methods, so it is not possible to introduce a Test Double to the SUT via Dependency Injection or Dependency Lookup to replace the library class during testing. This problem arises very often when we need to use system or third party libraries (like the .NET framework) where we can’t modify the library classes and have to use them as they are. Library designers prefer to use class-based APIs instead of interfaces, because they can be evolved in later versions of the library. If they want to add members to a library interface in a later version , they would break existing code [Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Librariesby Abrams and Cwalina]. Very often the SUT can’t be tested together with the library class, because the library class can’t be used in the test environment. The reason may be that the library class will not return values needed for the test or executing it would have undesirable side effects.

How it Works

We write our own interface which mirrors the API of a library class we are using in our SUT. Our own interface does not need to contain the complete API of the library class but may contain only the subset we are requiring for our SUT. We implement a thin wrapper for the library class which inherits from our own interface. The wrapper will contain no logic. Each method can simply be forwarded to the library class, because the signatures of our own interface are the same as the library class. The SUT must use the interface instead of the library class itself. The SUT will be initialized with a concrete object via Dependency Injection or Dependency Lookup. In the production environment the thin wrapper is used. In the test environment we can replace the thin wrapper with a Test Double.

When to Use It

We have to use the Own Library Interface when we use a third party library class in our SUT which has both of the two following characteristics:
  • The dependency on the library class prevents us from executing the SUT in a test environment. It may be plain impossible, too slow, too complex or too expensive to prepare a test environment for testing the SUT together with the library class.
  • The library class can not be replaced by a Test Double, because it does not inherit from an interface, it does not declare its methods as virtual or it has static methods.
These circumstances very often lead to the smell Developers Not Writing Tests. The SUT will be declared as untestable. Also TDD beginners often stumble over this problem and get the impression that TDD is not applicable to real world examples.

Implementation Notes

Library classes which define the API for operating system mechanisms (registry, event log, services), the API for hardware sub systems (network infrastructure) or the API to other software components (SMTP server, POP3 server) are candidates for the usage of the Own Library Interface pattern. Preparing a fixture for testing own classes which are using such library classes may be plain impossible, too slow, too complex or too expensive. See TDD for Beginners as an detailed example for the usage of the Own Library Interface pattern. We do not need to use the Own Library Interface pattern, when we can test our SUT together with the library class. For example the File or Directory classes from the .NET framework can easily be tested together with the SUT, because preparing files and directories during test setup as well as checking them after exercising the SUT is quite easy.

Saturday, April 19, 2008

To become a better programmer

I think some books might help to become a better programmer. This is my personal list:

Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)

The book came out, when I finished university and started by first full time job as an programmer. The theory of patterns taught me about the importance of names for concepts and the importance of communication with other developers. Five years later I went to a conference just to see Erich Gamma. Of course he spoke about patterns, but combined his talk with TDD, JUnit and a comparison of Java and C#. The lecture was not very long but brilliant. That was the first time I heard about TDD and got test infected.

Martin Fowler Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series)

I read the book, when I already worked on enterprise applications for several years. The book was an revelation. Most of the problems described there I know very well, but now I got names for them and so many alternative solutions. This book gave me the possibility to better reflect about design and architecture decisions. This book was partly responsible that I became the architect of our project.

Martin Fowler, Kent Beck, John Brant, and William Opdyke Refactoring: Improving the Design of Existing Code (Addison-Wesley Object Technology Series)

Beside the refactorings and the theory, this book helped me so much to convince my team members of the benefits of TDD.

Eric Evans Domain-Driven Design: Tackling Complexity in the Heart of Software

Brilliant book! The concept of the 'ubiquitous language' helped me very much for my day to day work. Using the 'Layered Architecture' pattern to separate technical details from the business concepts helped to better organize our software components.

Bertrand Meyer Object-Oriented Software Construction (Book/CD-ROM) (2nd Edition) (Prentice-Hall International Series in Computer Science)

Maybe this is the oldest book in my collection. Nevertheless it is still useful for me. I use assertions and 'programming by contract' nearly every day. This concepts can be used together with TDD very well. Even if you do not use Eiffel as the programming language, you can implement an assertion class for every other programming language in several minutes.

Mary Poppendieck and Tom Poppendieck Lean Software Development: An Agile Toolkit (Agile Software Development Series)

I never believed that other industries can teach the software industry about new concepts. After reading this book I know that the people from Toyota were very clever and the software people can learn a lot from them. Now I always try to find some 'waste' in our processes.

Kent Beck Extreme Programming Explained: Embrace Change (2nd Edition) (XP Series)

Although I never had the chance to work in a full blown XP project, this book is still a constant source of inspiration.

Kent Beck Test Driven Development: By Example (Addison-Wesley Signature Series)

If you start with TDD, read this book.

Gerard Meszaros xUnit Test Patterns: Refactoring Test Code (Addison-Wesley Signature Series)

If you already worked a little bit with TDD, then read this book.

I'm very sure everyone has its own list. I would be glad to here from other people about their favorite books.

Monday, March 31, 2008

Mail Attachments without files

I just received a comment about an article I wrote for www.codeproject.com. The article describes how to create and send mails with attachments in C# (no rocket science :-). The attachments are created in-memory without any file system access by the use of a memory stream: http://www.codeproject.com/KB/IP/InMemoryMailAttachment.aspx

Friday, March 28, 2008

TDD for Beginners

Recently a colleague of mine, which is a quite experienced programmer, wants to write his first code using TDD. It takes only minutes until he encountered the first obstacle. It seems that TDD is quite difficult for beginners. I will describe some of the problems and show code examples to help TDD beginners to become familiar faster with this excellent technique. Based on these kinds of experiences I described also a pattern called Own Library Interface which is applicable in the situation described below. My colleague needs to implement a background service, which monitors a database. The background service has to send notifications to one or more external receivers. He designed an EmailSender class, which can be initialized with all email related information like the smtp server, the sender and the receiver email addresses. Now he wants to write the SendToAll() method, which only needs some information for the receivers:
public void SendToAll(string subject, string details)
He has already poked around in the .NET framework and has found the SmtpClient class for easy sending of emails. He wants to use this class in his own EmailSender class. He knows that he first has to write a test, if he wants to follow the TDD principles, before he can begin with the implementation. He starts to implement the test method, which should verify the successful execution of the method:
[TestFixture]
public class EmailSenderFixture
{
  [Test]
  public void SendToAll()
  {
    // Setup
    EmailSender sender = new EmailSender();
    ...

    // Exercise
    sender.SendToAll("TestSubject","TestDetails");

    // Verify
    // ?
  }
}
How can he verify the outcome of the SendToAll method? One solution would be to let his own class send emails to an email account and then checking the correct behaviour of his class by retrieving the emails via POP3. This solution has some disadvantages:
  • The tests would be very slow.
  • The tests need special preconditions (context) to run (smtp server, email account).
  • The tests would not only cover the functionality of the class alone but also the .NET framework class SmtpClient. Framework classes do not need to be tested, because it can be assumed that they work correctly. (Even if they do not, we can't do anything about that)
  • The retrieval of emails via the POP3 protocol has to be implemented only for the automated tests, which are currently not need for the production system.
I would always prefer to use state verification, that means verifying the outcome of a method by inspecting the state of the manipulated object, but in this case the class has no state which can be verified. As we have seen, the state verification of a backdoor (a real email account) has many drawbacks. An other solution would be the use of a mock object as a test double for the SmtpClient. Currently our SendToAll method is empty and uses no dependent object, which can be mocked out. My colleague decided to use mock objects to verify the behaviour of his class. He starts implementing an initial version of his method, before he finishes his test method. The initial version looks like this:
public class EmailSender
{
 private SmtpClient smtpClient;
 ...
 public EmailSender(
  SmtpClient smtpClient,
  string host,
  int port,
  string from,
  params string[] recipients)
 {
  this.smtpClient = smtpClient;
  this.from = from;
  this.port = port;
  this.host = host;
  this.recipients = recipients;
 }

 public void SendToAll(string subject, string details)
 {
  smtpClient.Host = host;
  smtpClient.Port = port;

  foreach (string recipient in recipients)
  {
      smtpClient.Send(
   from,
   recipient,
   subject,
   details);
  }
 }
}
He already injected the SmtpClient object via the constructor and uses this object to send the emails. This is a nice try but unfortunately he can't mock out the SmtpClient yet. The SmtpClient framework class does not inherit from any interface nor does it declare its methods as virtual, so he can't create a mock object for SmtpClient. This lack of 'mockability' is quite common for most of the classes in the Microsoft .NET framework. Cwalina and Abrams [1] are describing rules for the design of framework classes: "Class-based APIs can be evolved with much greater ease than interface-based APIs because it is possible to add members to a class without breaking existing code". From the perspective of framework designers it is absolute understandable, that most of the classes do not use interfaces. As unit test authors we have to write our own interfaces which mirror the API of the framework classes as close as possible and later write very thin wrappers inheriting from our interface. My colleague only uses two properties and one method of the SmtpClient class. He only needs to declare these members in his new interface:
public interface ISmtpClient
{
 string Host { get; set; }
 int Port { get; set; }
 void Send(string from, string recipients,
      string subject, string body);
}
Now he can slightly modify his EmailSender class to use the ISmtpClient interface instead of SmtpClient framework class directly:
public class EmailSender
{
 private ISmtpClient smtpClient;
 ...
 public EmailSender(
  ISmtpClient smtpClient,
  string host,
  int port,
  string from,
  params string[] recipients)
 {
  this.smtpClient = smtpClient;
  ...
 }
 ...
}
He finishes his test and verifies the behaviour of the EmailSender class. He is using the NMock2 framework for his mock object:
using NMock2;
...
[Test]
public void SendToAll()
{
 // Setup
 Mockery mocks = new Mockery();
 ISmtpClient smtpClientMock = mocks.NewMock<ISmtpClient>();

 EmailSender sender = new EmailSender(
  smtpClientMock,
  "smtp.test.com",
  25,
  "sender@test.com",
  "receiver1@test.com",
  "receiver2@test.com");

 Expect.Once.On(smtpClientMock).
  SetProperty("Host").
  To("smtp.test.com");
  Expect.Once.On(smtpClientMock).
  SetProperty("Port").To(25);

 // We expect that the Send method is called for every recipient
 Expect.Once.On(smtpClientMock).Method("Send").
  With("sender@test.com", "receiver1@test.com",
       "TestSubject", "TestDetails");
  Expect.Once.On(smtpClientMock).Method("Send").
  With("sender@test.com", "receiver2@test.com",
       "TestSubject", "TestDetails");

 // Exercise
 sender.SendToAll("TestSubject", "TestDetails");

 // Verify
 mocks.VerifyAllExpectationsHaveBeenMet();
}
This test runs very fast and it does not need any special context like an smtp server or an email account. Before he can use the EmailSender class in a production environment he has to implement a thin wrapper around the SmtpClient framework class:
public class SmtpClientWrapper : ISmtpClient
{
 private SmtpClient smtpClient = new SmtpClient();

 public string Host
 {
  get { return smtpClient.Host; }
  set { smtpClient.Host = value; }
 }

 public int Port
 {
  get { return smtpClient.Port; }
  set { smtpClient.Port = value; }
 }

 public void Send(string from,
  string recipients,
  string subject,
  string body)
 {
  smtpClient.Send(from, recipients, subject, body);
 }
}
This wrapper needs not to be tested, because it adds no new functionality to the framework class. The EmailSender class can now be used in the background service:
public void Run()
{
 EmailSender sender = new EmailSender(
  new SmtpClientWrapper(),
  "smtpserver.xy.com",
  25,
  "sender@xy.com",
  "receiver1@xy.com",
  "receiver2@xy.com");

 while (!stopped)
 {
  // Check something
  string checkResult = Check();

  // Send email
  sender.SendToAll("Check", checkResult);

  // Sleep for 20 minutes
  Thread.Sleep(20*60*1000);
 }
}

Conclusion

Applying TDD as a new technique for software development is sometimes not easy for beginners. When we need to write software, which has to use framework classes, we need to use mock objects and we eventually have to introduce new interfaces and wrappers. The same problems we saw with SmtpClient arise when we have to use classes like System.ServiceProcess.ServiceController, System.Diagnostics.EventLog, System.DirectoryServices.ActiveDirectory.Domain, System.Net.NetworkInformation.NetworkInterface, System.Net.Sockets.Socket, System.Environment, Microsoft.Win32.Registry just to name a few. I hope this article can help a little bit to overcome the first hurdles when using TDD the first time.

References

[1] Cwalina, K., Abrams, B.: Framework Design Guidelines, Microsoft .NET Development Series, Addison Wesley, 2006