Easily add test-dependencies in debug-mode

by Kenny Eliasson 12. March 2010 11:15

Something I often want to do is to replace some implementations of my interfaces that touches external resources (like hitting the database or sending mails).

I've got a MailService class that i have a "debug-implementation" of that looks like this


public class DebugMailService : IMailService
{
    public void Send(MailMessage message)
    {
        Send(new List<MailMessage> { message});
    }

    public void Send(IEnumerable<MailMessage> messages)
    {
        foreach (var mailMessage in messages) {
            Debug.WriteLine(string.Format("Skickar mail till {0} från {1}", mailMessage.To[0].Address, mailMessage.From.Address));
        }
    }
}

Inside my IoC-container setup (in my case StructureMap) i checks to see if the I'm in debug with the preprocessor directive #if (DEBUG) and sets a private variable to true. Like below


    public class StructureMapSetup
    {
        private bool _isDebugMode;

        public void Execute()
        {
            #if (DEBUG)
                _isDebugMode = true;
            #endif
   
            ObjectFactory.Initialize(x =>
            {
                x.AddRegistry(new BootstrapperRegsitry());
                x.AddRegistry(new UnitOfWorkRegistry());
                x.AddRegistry(new AnalyticsRegistry(_isDebugMode));
                x.AddRegistry(new RepositoryRegistry());
                x.AddRegistry(new FluentMdxRegistry(_isDebugMode));

            });
      }



Later on in my Registry classes i can easily check if im in debug mode and add the correct concrete class I would like under debug-circumstances


if (isDebugMode) {
    For<IAuthenticationService>().Use<DebugAuthentication>();
    For<IMailService>().Use<DebugMailService>();
} else {
    For<IAuthenticationService>().Use<CIRAuthentication>();
    For<IMailService>().Use<QuicksearchMailService>();
}


Sweet, and I dont need to change one line of code when going to production or Q/A (since I build in release mode then).

 

Over 'n out

Tags:
Categories: C#

Comments

trackback
DotNetKicks.com on 3/16/2010 7:31:48 AM

Easily add test-dependencies in debug-mode

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading