Philly.Net recently had a very successful event called CSharpenUp. We spent the day talking about some advanced topics for C# developers. We had 4 speakers and 80+ attendees. The feedback was very positive, everyone learned a lot and had fun too. If we can set it up, we’ll do the same event in the fall for those that missed it.

I’m still gathering code samples from the other presenters. But for now, here is mine:

Code samples and slides for my LINQ session: Intro to LINQ

Code samples and slides for my Unit Testing session: Unit Testing Made Easy

Also, FYI we did try to record the sessions using Camtasia. Unfortunately, the mic we used wasn’t that great. I’m trying to salvage mine but I may just re-record them.

When I write code, one of my big concerns is how will I test it. I’ve learned that when I see a static method, it is going to make things more complicated than I would like. However, resolving that isn’t usually too difficult. Converting a string value into an Enum is a perfect example. Of course, parsing the string may succeed or fail and I need to know how my code will behave in either case, hence the reason for the unit tests.

In order to make unit testing a bit easier, I wrote a simple class to help out. Basically, this class “wraps” Enum.TryParse() and of course, implements and interface. I’m also using some simple generics to make the casting a little prettier. Since I used an interface, I can now using MOQ, RhinoMocks, or any other framework to mock my dependency and control how it behaves.

You may note that I didn’t call the methods Parse. Instead, I used the name Adapt. That is just a naming convention of my current project so it made sense to be consistent. Feel free to rename this as you wish :)

Here is the interface:

public interface IStringToEnumAdapter
{
     T Adapt<T>(string value) where T: struct;
     bool TryAdapt<T>(string value, out T? result) where T : struct;
}

You’ll probably notice that my generic constraint is struct. That is because you can’t use Enum as a generic constraint. So struct is the best I’ve got to work with. And considering we are doing parsing here, if you pass any other stuct in, it is going to fail on the parse anyway. So I think it is pretty safe.

Here is the implementation:

public class StringToEnumAdapter : IStringToEnumAdapter
{
    public T Adapt<T>(string value) where T : struct
    {
        T result;
        
        bool success = Enum.TryParse(value, true, out result);
 
        if (success)
            return result;
 
        throw new InvalidEnumArgumentException(string.Format("{0} could not be converted to {1}", value, typeof(T).Name));
    }
 
    public bool TryAdapt<T>(string value, out T? result) where T : struct
    {
        T parsedValue;
        bool success = Enum.TryParse(value, true, out parsedValue);
 
        result = success ? parsedValue : (T?)null;
 
        return success;
    }
}

Guess what? It isn’t all that complicated right? If you are getting into testing, you’ll soon find out that simple steps like this make life a lot easier.

Click here to download the class and unit tests for it too.

Last night I had the pleasure of presenting “Unit Testing Made Easy” at NoDeNUG (Northern Delaware .Net User Group).  I’ll be doing the same demo at Philly.Net Code Camp next week.  The NoDeNUG crowd was great and asked good questions.  That made the demo fun for me and I think it went very well.  I hope it goes over great at Code Camp too. 

I’m attaching a zip file containing my slides and Visual Studio Solution.  The demo should work fine on it’s own, the references to NUnit, MOQ, and StructureMap are all included.  But if you don’t have VS2010 with Premium or Ultimate and Feature Pack 2, the CodedUI (testing for Silverlight UIs) won’t work.  I hope it will build and run ok though.  If not, let me know and I’ll upload the solution without references to the Coded UI stuff.  Also, the demo uses a Silverlight application for the front end.  If you don’t have the Silverlight tools set up, you can either add them to Visual Studio, or simply exclude the Silverlight projects.  You’ll still be able to run the services and the unit tests, even if you can’t see how the UI looks.

If you’ve just come across this and haven’t heard my presentation you have two options:

1. Come to Philly.Net Code Camp next week (April 9) and hear the presentation then!

2. Just open the enclosed solution and have a look!  I’ve got sample code in there to demonstrate using Dependency Injection to make services easier to unit test, sample unit tests, and sample tests using mocking of dependencies.  I’m coding my tests with NUnit, using StructureMap for my IOC, and MOQ as my mocking framework.

Here is the code:  UnitTestingMadeEasy.zip

Again, if you have any problems with the solution, let me know and I’ll upload a copy without the Coded UI, or even without the Silverlight part.

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.