I’ve said this so many times, writing unit tests is easy if the code was written well in the first place.  And when I say “written well”, what I really mean is “written to be testable”.

So here is the situation:  I have a simple service that does some logging, most of the details are not important.  But in the LogDebug() method, the code checks the web.config file to see if the debug logging is enabled.  That too in itself is pretty simple stuff.  Typically it would look like this:

bool configDebugMode = bool.Parse(WebConfigurationManager.AppSettings["Logging.Debug"]);

EDIT: I should point out what I mean when I say below that testing this code isn’t very easy. Sure, testing it is easy if I only want to test one value from the web.config file, such as ‘true’. But in this situation, I want to test when the config file value is ‘true’, and also when it is ‘false’.

But testing that isn’t very easy at all.  You’d have to do some crazy stuff with multiple config files or something.  But if the code was written differently, it’s very easy to test.  The key is to wrap the call to WebConfigurationManager in another class that implements and interface, then use dependency injection.  And with the class designed like that, you can use a simple mock to make the testing simpler.  It’s really easy, here is how I’m doing it.

First I define an interface, I’m calling it IConfigurationManager: 

public interface IConfigurationManager
{
    string GetAppSetting(string key);
    ConnectionStringSettings GetConnectionString(string key);
}

The interface has two simple methods so I can use it to get AppSettings and ConnectionStrings.  Could be I’ll need to add some more methods later but I don’t need them yet.  Next I implement the interface in a concrete class that can get the values from the web.config.  This too is really simple.  I’m calling this class WebConfigConfigurationManager.  That may sound weird and redundant but it tells me that it is a ConfigurationManager that gets values from WebConfig.  If I need an implementation that pulls values from a db I could make another one called DbConfigurationManager.  Here is the code:

public class WebConfigConfigurationManager : IConfigurationManager
{
    public string GetAppSetting(string key)
    {
        return WebConfigurationManager.AppSettings[key];
    }

    public ConnectionStringSettings GetConnectionString(string key)
    {
        return WebConfigurationManager.ConnectionStrings[key];
    }
}

So far this is was pretty easy to write and you can see it isn’t too complicated so it should work pretty well.  But this doesn’t make it any more testable.  The key to making it testable is Dependency Injection.  My LoggingService will “depend on” this WebConfigConfigurationManager class.  But instead of just instantiating WebConfigConfigurationManager within LoggingService, I’ll inject it in.  By doing that, I’ll also be able to inject something different during unit tests.  Hang in there, I’ll show you how.  First, here is the injection part, it is much simpler than it sounds. I inject the dependency via the constructor, you’ll note I am injecting a few other dependencies too:

public LoggingService(IEnterpriseLoggingRepository loggingRepository,
                        ILoggingInformationAdapter loggingAdapter,
                        IConfigurationManager configurationManager)
{
    if (loggingRepository == null) { throw new ArgumentNullException("loggingRepository"); }
    _loggingRepository = loggingRepository;

    if (loggingAdapter == null) { throw new ArgumentNullException("loggingAdapter"); }
    _loggingAdapter = loggingAdapter;

    if (configurationManager == null) { throw new ArgumentNullException("configurationManager"); }
    _configurationManager = configurationManager;
}

If you were expecting something fancy, sorry to disappoint you. The Dependency Injection part is pretty simple too.  Here is the LogDebug() method too.  Please don’t worry about the details of _loggingAdapter.ToDomainModel().  That is something I need to turn the “message” into something that the LoggingRepository can work with. 

public void LogDebug(string message)
{
    try
    {
        //are we in debug mode?
        bool configDebugMode = bool.Parse(_configurationManager.GetAppSetting("Logging.Debug"));

        if (!configDebugMode)
            return;

        //convert the message into something the logging repo can use.
        LoggingData data = _loggingAdapter.ToDomainModel(message);

        //log it!
        _loggingRepository.LogDebug(UiSystem, data);
    }
    catch (Exception loggingException)
    {
        // if an exception occurred during logging, capture the message that was being logged in the first place
        throw new LoggingException(loggingException) { OriginalMessage = message };
    }
}

OK the code is written, so how does this make the testing easier?  Since the tough to test code is in a dependency, when I write the test, I can inject something different in.  In this case, I want to inject in a class that I can easily control and return either true or false for the Logging.Debug setting.  There are a bunch of ways to do this, I’ll use a mocking framework to help.  In this case I’m using MOQ.  Here’s most of the code from my NUnit TestFixture (I took out a bunch of extra tests for brevity.  An explanation follows.

[TestFixture]
public class LoggingServiceTests
{
private Mock<IEnterpriseLoggingRepository> _loggingRepository;
private Mock<ILoggingInformationAdapter> _adapter;
private Mock<IConfigurationManager> _configurationManager;
private LoggingService _loggingService;

[SetUp]
public void Setup()
{
    _loggingRepository = new Mock<IEnterpriseLoggingRepository>();
    _adapter = new Mock<ILoggingInformationAdapter>();
    _configurationManager = new Mock<IConfigurationManager>();
    _loggingService = new LoggingService(_loggingRepository.Object, _adapter.Object, _configurationManager.Object);

}

[Test]
public void LoggingDebugIsSkippedIfConfigSettingIsFalse()
{
    _configurationManager.Setup(cm => cm.GetAppSetting("Logging.Debug")).Returns("false");

    _loggingService.LogDebug("This is a test");

    _adapter.Verify(a => a.ToDomainModel(It.IsAny<string>()), Times.Never());
    _loggingRepository.Verify(lr => lr.LogDebug(It.IsAny<string>(), It.IsAny<LoggingData>()), Times.Never());
}

[Test]
public void LoggingDebugIsExecutedIfConfigSettingIsTrue()
{
    _configurationManager.Setup(cm => cm.GetAppSetting("Logging.Debug")).Returns("true");

    _loggingService.LogDebug("This is a test");

    _adapter.Verify(a => a.ToDomainModel(It.IsAny<string>()), Times.Exactly(1));
    _loggingRepository.Verify(lr => lr.LogDebug(It.IsAny<string>(), It.IsAny<LoggingData>()), Times.Exactly(1));
}

If you aren’t familiar with Mocking or MOQ, you may want to read up on the topic.  I’ll try to hit the highlights.  Check out the SetUp() method.  You can see that instead of using “real” classes, I instantiate a bunch of Mocks so I can control them easily.  In the last line of the method I “inject” the mocks into the LoggingService.  Next, let’s examine the method LoggingDebugIsSkippedIfConfigSettingIsFalse().  The first line of code pretty much says when the ConfigurationManager’s GetAppSetting() method is called with the argument “Logging.Debug”, just return false.  I really like the MOQ syntax, if you are used to Lambda expressions, the MOQ stuff reads pretty easily, I think.  The mock class won’t actually look at a config file or anything.  Remember, this is a mock so there is no implementation.  With code like this, you can actually step through with the debugger and see the mocks act as you told them too!  If you look back to the actual LogDebug() method you will see that if the Logging.Debug value is false the method simply ends.  So then the last two lines of code in the test verify that the adapter’s ToDomainModel() and the logging repository’s LogDebug() method are never called at all!  That’s all there is to it.  Plus the second unit test shown here does the opposite, it makes sure that all of the code is executed if Logging.Debug is set to true.

I can assure you it took me a lot longer to write this blog post than it did to code the IConfigurationManager, WebConfigConfigurationManager, and LoggingServiceTests.  I hope you find this code helpful.

Code snippets are a great time saver and they are pretty simple to create.  Any time you find yourself typing the same thing over and over again, you may want to consider creating your own code snippet to make life easier.

Here’s an example… I was recently working on a large refactor of some error handling code for a user interface.  Basically, I went from form to form, refactoring the way the error handling was implemented and then test it.  How did I test it?  By throwing exceptions in my code.  Doing so is pretty easy, just find the portion of code that needs to be tested and type “throw new Exception(“This is a test”);”  Plus, for good measure and safety I’d add this above it: “//TODO – Don’t forget remove this test code”

//TODO:  Don't forget to remove this test code:
throw new Exception("This is a test");

Sure, it is easy enough to type but it got old pretty quick and I decided to create a simple snippet.  Once I did, all I needed to type was “tne” (it stands for “Throw New Exception) and hit “tab” twice (hitting “Tab” twice tells Visual Studio to use the code snippet based on what you just typed).  Sounds cool huh?  Ok so here is how you create a simple code snippet…

Snippets are stored in XML files on your pc.  To create a new one, it is easiest to just start with an existing snippet and modify the xml to meet your needs.  Here is an example of the one I am using:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Throw new Exception</Title>
      <Shortcut>tne</Shortcut>
      <Description>This will generate code to throw a new Exception</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[    //TODO: Remove this test code:
        throw new Exception("An Exception has been thrown"); $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

If you want to use your own snippet, just change the Title, Shortcut, Description and Author elements.  And of course, you need to put your snippet inside of the CDATA area of the the Code Element.

Next, you just need to save this file in a place where Visual Studio will pick it up.  To tell VS2008 where to look for it, go to Tools > Code Snippets Manager.  Make sure you select the correct language in the drop down, otherwise Visual Studio can’t connect your snippet to the language you meant it for.  You’ll also notice the existing folders for snippets.  That may give you an idea of where you should store your own snippets ;).

You can also write more complex snippets that allows you to use the snippet and then type in values that get used within the snippet.  For instance, I do a lot of work with Silverlight and for databinding my public variables must implement INotifyPropertyChanged.  Instead of manually typing a property that does so, plus a backing variable, I use a snippet with the shortcut “npc”.  In the sample below, you will see the words TYPE, PROPERTY and FIELD highlighted in Green.  Those are placeholders and when I utilize the code snippet, VS will prompt me to replace those values.  So if I want to create a public property and backing variable for a string FirstName, I just type the following:  “npc” TAB TAB “string” TAB “FirstName” TAB “_firstName” (but don’t type the quotes!).  It may seem weird at first but makes coding much easier.

private TYPE FIELD; 

image

Here is the XML for my “NotifyPropertyChanged” snippet:

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Notify Property Changed Property</Title>
      <Shortcut>npc</Shortcut>
      <Description>Code snippet for creating a property with a backing variable that calls NotifyPropertyChanged</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>The Type for the Property</ToolTip>
          <Default>TYPE</Default>
        </Literal>
    <Literal>
          <ID>fieldname</ID>
          <ToolTip>The Type for the field</ToolTip>
          <Default>FIELD</Default>
        </Literal>
    <Literal>
          <ID>propertyname</ID>
          <ToolTip>Parameter name</ToolTip>
          <Default>PROPERTY</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
    public $type$ $propertyname$ {
    get { return $fieldname$; } 
    set 
    { 
    if ($fieldname$ != value) 
    { $fieldname$ = value; 
    NotifyPropertyChanged("$propertyname$");
    }
    }
    }
    private $type$ $fieldname$; 
    $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Unfortunately, there isn’t a Code Snippet Editor included in VS.  There is some kind of plug-in available for creating VB snippets but I’ve never used it.  I’m sure you can find it with your favorite search engine.  Still it is pretty easy to write these yourself.