Archive for the ‘Unit Testing’ Category


You are currently browsing the archives for the Unit Testing category.

Archives

  • Categories

  • Isolating Your Configuration Files For Testability

    Tuesday, July 27th, 2010

     

    Ben Hall over at CodeBetter just posted a nice article on using the Castle Dictionary Adapter to isolate your code from the ConfigurationManager class to make your unit tests easier to write.

    I thought I might take the opportunity to talk about a technique that we use to isolate our code from ConfigurationManager and also other system classes such as the system DateTime, using the language constructs built within the .Net Framework version 3.5 and above. I’m not saying that this technique is better than the Castle Dictionary Adapter method but it just highlights an alternative approach that is possible without using third party assemblies.

    Ok so using Ben’s example, because I’m too lazy to think up my own, we have an application configuration value for our EnableNewsLetterSignup.

    <add key="EnableNewsletterSignup" value="false"/>

    In our code we pull out the value using the static method on the ConfigurationManager class like so.

    public bool Signup(string email)

    {

        if (!Boolean.Parse(ConfigurationManager.AppSettings["EnableNewsletterSignup"]))

            return false;

     

        return true; // technically this would go off to an external web service

    } 

    Ok so nothing new here but when it comes to testing this code it means that we have to have a configuration file for our unit test project (which is bad) and we can only ever test one path through the code without changing the value of the configuration file. Which means we some untestable code without doing some configuration Kung Fu on our config file which is more work than we should have to do.

    Wrapping It Up

    The technique we use is to wrap our class up in a static wrapper class which we will call Config. For our corresponding application setting we add a public static field of the same name for clarity, of type Func<string>. Now the important thing is we give it it’s default behaviour which in this case is to go off and use our old friend ConfigurationManager to determine whether or not our newsletter is enabled or not.

    public static class Config

    {

        public static Func<string> EnableNewsletterSignup = () => ConfigurationManager.AppSettings["EnableNewsletterSignup"];

    }

     

    Writing Our Code

    Now going back to our code where we use the application setting it will now look something like this.

    public bool Signup(string email)

    {

        if (!Boolean.Parse(Config.EnableNewsletterSignup()))

            return false;

     

        return true; // technically this would go off to an external web service

    } 

     

    Testing Our Code

    So now when we want to unit test this piece of code we simply change the default behaviour of our Config class to the behaviour we want to test. See line 5 below, where we force it to return false for the purpose of our unit test. We now have total control over what our supposedly configuration value is without ever having to touch the file system.

       1: [Test]

       2: public void If_our_newsletterSignup_is_not_enabled_we_should_not_be_signed_up()

       3: {

       4:     // Arrange

       5:     Congig.EnableNewsletterSignup = () => "false";

       6:  

       7:     // Act

       8:     var isSignedUp = _classUnderTest.Signup("emailaddress@foo.com");

       9:  

      10:     // Assert

      11:     Assert.IsFalse(isSignedUp);

      12: }

     

    Other Uses

    As I said earlier this technique can also be quite useful for isolating other system dependant classes such as code that uses the DateTime.Now property. Sometimes if you want to logic concerning dates and times it can be pretty hard to control the flow of the code because the DateTime is generated by the system. How for example do you test something if you need to be some date in the future or some date in the past. The code below can be used in the same way to isolate our tests from the underlying call to the DateTime.Now which can be overriden as required to give the behaviour we want.

    public static class SystemDateTime

    {

       public static Func<DateTime> Now = () => DateTime.Now;

    }

    Conclusion

    This approach offers an alternative solution to using the Castle Dictionary Adapter,  and although it requires writing slightly more code it does mean that it is one less assembly that you have to reference in your project which can be a good thing sometimes.

    Mocking HtmlHelpers in ASP.Net MVC

    Friday, December 4th, 2009

    NB: This post relates to version 1 of ASP.Net MVC

    I recently added a static extension method for generating a custom drop down list and wanted to test it using Rhino Mocks (version 3.5).
    One issue I kept banging my head against was how to create a Mock HtmlHelper in order to call the method correctly.
    A number of posts later, and various attempts at using some of the sample code and I finally came across this post detailing a bunch of MVC tests.

    After a minor amount of customising, I ended up with the following, which works like a charm for me to use in my tests.

            ///
            /// Creates a HTML helper for use in tests.
            ///
            private HtmlHelper CreateHtmlHelper()
            {
                var userControl = new ViewUserControl();
                var container = new ViewPage();
                container.Controls.Add(userControl);
                var context = MockRepository.GenerateMock<ViewContext>();
                userControl.ViewContext = context;
    
                return userControl.Html;
            }

    Using RhinoAutoMocker with Property Injection.

    Tuesday, November 3rd, 2009

    I am a big fan of using StructureMap’s Automocker when unit testing as it stops me writing a lot of repetitive code.

    If you haven’t used it before go and have a look, all you need to do is download StructureMap from here and reference the StructureMap.AutoMocking.dll.

    What does an AutoMocking container do? Well consider the following class.

            public ExampleClass(IDependency1 dependency1, IDependency2 dependency2)
            {
                _dependency1 = dependency1;
                _dependency2 = dependency2;
            }
    

    If we wanted to test this class we would most probably use our Mocking framework to create mocks for our dependencies and inject them into the class. This is fine buts its repetitive coding. When you use an Automocking container it looks at the constructor for you and creates the mocks for you saving you all that effort.

    Derik Whittaker has a much better post on why you should use an AutoMocker here..

    Anyway there is one thing that RhinoAutoMocker doesn’t do and is allow you inject your dependencies into a class using property injection. Now 99% of the time I would recommend using constructor injection however there are times when your IOC container won’t know the whole dependency chain at the time of your object creation and must inject it at a later stage..Anyway that sounds like the topic for another post.

    So if you want to use RhinoAutoMocker and still be able to set any dependencies using property injection here is an extension method that will allow you to do this.

      public static void RegisterPropertyDependency<TARGETCLASS, TProperty>(
                this RhinoAutoMocker<TARGETCLASS> autoMocker, Expression<Func<TARGETCLASS, TProperty>> expression)
                where TARGETCLASS : class
            {
                var body = expression.Body as MemberExpression;
    
                if (body != null)
                {
                    // Work out the type from our expression tree.
                    var propertyInfo = (PropertyInfo) body.Member;
                    var propertyType = propertyInfo.PropertyType;
    
                    // We know the property type now so
                    // we can create a Stub of it using Rhino Mocks.
                    var mockDependency = MockRepository
                                       .GenerateStub(propertyType, null);
    
                    // inject in our stub.
                    autoMocker.Inject(propertyType, mockDependency);
    
                    var propertyName = propertyInfo.Name;
    
                    var classUnderTestType = autoMocker.ClassUnderTest.GetType();
    
                    var dependencyPropertySetMethod = classUnderTestType.GetProperty(propertyName).GetSetMethod();
    
                    dependencyPropertySetMethod
                .Invoke(autoMocker.ClassUnderTest, new[] {mockDependency});
                }
            }
    

    Now consider our example class again with its second dependency being injected through a property.

        class ExampleClass
        {
            private readonly IDependency1 _dependency1;
    
            public ExampleClass(IDependency1 dependency1)
            {
                _dependency1 = dependency1;
            }
    
            public IDependency2 Dependency2 { get; private set; }
        }
    

    To test test this class we need to tell the AutoMocker that the property is to be used for property injection like so.

    
            var autoMocker = new RhinoAutoMocker<ExampleClass>();
    
            automocker.RegisterPropertyDependency(classUnderTest =>  classUnderTest.Dependency2);
    

    Now we can access the mock object to set its behavior through the Auto mocker as we would any other dependency created by the Auto mocker.

    
            var autoMocker = new RhinoAutoMocker<ExampleClass>();
    
            automocker.Get<IDependency2>()
                            .Stub(x =>  x.SomeMethod())
                            .Return(true);
    

    Testing your StructureMap Registries.

    Monday, November 2nd, 2009

    I find that on every project I work on which uses StructureMap I include the same three unit tests per Structuremap registry.

    My TestFixture set up normally looks something like this..

            [TestFixtureSetUp]
            public void TestFixtureSetup()
            {
                // Act
                ObjectFactory.Initialize(x => x.AddRegistry(new MyRegistry()));
            }
    

    My first tests makes use of the in built testing capabilities within StructureMap. If there are any problems with your registry they should be captured by this test.

            [Test]
            public void Assert_registry_is_valid()
            {
                // Assert
                ObjectFactory.AssertConfigurationIsValid();
            }
    

    My second test isn’t really a test but is useful to have in your solution if you need to diagnose any StructureMap problems. Calling this will write out all the dependencies that are registered with your container to the output window.

             [Test]
            public void What_do_we_have()
            {
                Debug.WriteLine(ObjectFactory.WhatDoIHave());
            }
    

    My third test checks that you have more than one dependency registered with your StructureMap container. What I have found is that it is possible to configure your registry incorrectly and StructureMap won’t load any dependencies at all. However when you call the AssertConfigurationIsValid method it returns true. When you run up your application you get the ‘No Default Instance defined for PluginFamily’ exception. This tests helps you get check for this scenario.

             [Test]
            public void Assert_container_is_not_empty()
            {
                // Assert
                Assert.IsTrue(ObjectFactory.Container.Model.AllInstances.Count() > 1);
    
            }
    

    Mocking LightSpeed Units Of Work

    Tuesday, May 12th, 2009

    One of my colleagues asked me the other day how he could mock a LightSpeed UnitOfWork. Apparently he couldn’t find any good examples out there on the InterWeb so I thought I’d post this short code sample to show how its done.

    The most important thing is that you should not create your UnitOfWork yourself but use the CreateUnitOfWork() factory method on your LightSpeedContext. See code example below.

    using (var unitOfWork = Repository.Context.CreateUnitOfWork())
     {
            var customerOverEighteenYearsOld = unitOfWork
                                  .Customers
                                  .Where(customer => customer.Age > 18);
           return customerOverEighteenYearsOld.ToList();
     }
    

    Now if we wanted to test this code by mocking our UnitOfWork we can substitute our IQueryable<Customers> with an in memory collection rather than hitting the database directly.

    So our unit test setup code would look something like this. The example below uses Rhino Mocks to mock the Unit Of Work.

    [SetUp]
    public void TestSetUp()
    {
             // Customer Collection
             var customers = new List<Customer>{
                                    new Customer{Age = 10},
                                    new Customer{Age = 18}
                                    }; 
    
             var unitOfWorkFactory = MockRepository.GenerateStub<IUnitOfWorkFactory>();
             var unitOfWork = MockRepository.GenerateStub<CustomersUnitOfWork>(); 
    
             // Replace the normal UnitOfWorkFactory with our implementation.
             Repository.Context.UnitOfWorkFactory = _unitOfWorkFactory; 
    
             // Stub the behaviour of our unit of work factory to
             // return our mocked UnitOfWork
             unitOfWorkFactory
                        .Stub(uowf => uowf.Create(Arg<LightSpeedContext>.Is.Anything))
                        .Return(unitOfWork ); 
    
             // Stub our unit of work to return our in memory customer collection.
             unitOfWork.Stub(uow => uow.Customers()).Return(customers);
    }
    

    So all we really need to do is to mock our LightSpeed UnitOfWork Factory replacing the default factory on our LightSpeed Context with our mocked version.  

    We can then stub out the Create method on our mocked UnitOfWork factory to return our own implementation of our UnitOfWork (which is also a mock).  

    We can now get our UnitOfWork to behave as we want it to without ever having to hit a database.

    kick it on DotNetKicks.com

    Unit Testing LightSpeed Entities

    Thursday, April 2nd, 2009

    If you have not heard of LightSpeed or had a play with it then you should check out the excellent lightweight ORM from the boys at Mindscape.  I have worked with it for a couple of years now and really like it for certain type of projects, I think its simplicity is a good stepping stone for developers making that transition from old data access strategies to ORM technologies.

    The one thing I don’t like about it is that your domain objects are not persistant ignorant of the underlying ORM technology, and have to inherit from an Entity base class.

    I have run into problems when trying to unit test code that use my Lightspeed entities because I cannot just create a new entity without hitting the database.  Normally when you request an entity from the database the construction of that entity is handled by the Lighspeed framework.

    Some of the things that were causing me problems were:

    • I could not assign my own Id for the entity.
    • The Entities throw an exception if they don’t have UnitOfWork set.
    • Could not set up EntityCollection relationships between domain objects as they are read only properties.

    In the end I created a LightSpeedEntityFactory and some helper methods for testing purposes to create my entities and get around some of these issues.  I hope you find the following code useful.

        ///
    
        /// Factory class for building LightSpeedEntity, that are are divorced from a real UnitOfWork.
        /// 
    
        /// To be used for Unit Testing purposes only!
        internal class LightSpeedEntityFactory
        {
            #region Methods
    
            ///
    
            /// Build a LighSpeed Entity with the chosen Id, and a Fake UnitOfWork.
            /// 
    
            /// 
            /// 
            public static T Build<T>(object id) where T : Entity
            {
                var lightSpeedEntity = Build<T>();
    
                lightSpeedEntity.SetId(id);
    
                return lightSpeedEntity;
            }
    
            ///
    
            /// Build a LighSpeed Entity with a Fake UnitOfWork.
            /// 
    
            /// 
            /// 
            public static T Build<T>() where T : Entity
            {
                var lightSpeedEntity = (T)Activator.CreateInstance(typeof (T));
    
                IUnitOfWork unitOfWork = new UnitOfWork();
    
                lightSpeedEntity.SetUnitOfWork(unitOfWork);
    
                return lightSpeedEntity;
            }
    
            #endregion Methods
        }
    
       ///
    
        /// Some helper extension methods for changing the internals of a LightSpeed entity.
        /// 
    
        /// 
        /// We do some very naughty stuff in here using reflection and these methods
        ///  should only be used for the purposes of Unit Testing.
        /// 
        public static class LightSpeedHelper
        {
            #region Methods
    
            ///
    
            /// Set the Id of a LightSpeed Entity. This is usually only a read-accessible property.
            /// 
    
            public static void SetId(this Entity entity, object id)
            {
                var setIdInternalMethod = entity.GetType().GetMethod("SetIdInternal", BindingFlags.NonPublic | BindingFlags.Instance);
    
                setIdInternalMethod.Invoke(entity, new[] {id});
            }
    
            ///
    
            /// Sets a read-only property on a LightSpeed Entity.
            /// For setting up an object for testing purposes only.
            /// 
    
            /// lightspeedEntity.SetProperty(a => a.Addresses).SetValue(addresses)
            /// 
            /// The type of the ESULT.
            /// 
            public static IPropertySetter<RESULT> SetProperty<T, RESULT>(this T entity, Expression<Func<T, RESULT>> action) where T : Entity
            {
                var outerMember = (MemberExpression)action.Body;
    
                var outerProp = (PropertyInfo)outerMember.Member;
    
                var propertyName = outerProp.Name;
    
                IPropertySetter<RESULT> propertySetter = new PropertySetter<RESULT>(entity, propertyName);
    
                return propertySetter;
            }
    
            ///
    
            /// Sets the unit of work on a LighSpeed Entity.
            /// 
    
            public static void SetUnitOfWork(this Entity entity, IUnitOfWork unitOfWork)
            {
                var uowProperty = entity.GetType().GetProperty("UnitOfWork", BindingFlags.NonPublic | BindingFlags.Instance);
    
                uowProperty.SetValue(entity, unitOfWork, null);
            }
    
            #endregion Methods
        }
    
        public class PropertySetter<T> : IPropertySetter<T>
        {
            #region Fields
    
            private readonly object _parent;
            private readonly string _propertyName;
    
            #endregion Fields
    
            #region Constructors
    
            public PropertySetter(object parent, string propertyName)
            {
                _parent = parent;
                _propertyName = propertyName;
            }
    
            #endregion Constructors
    
            #region Methods
    
            public void SetValue(T value)
            {
                var fieldName = FormatPropertyName(_propertyName);
    
                var fieldInfo = _parent.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
    
                fieldInfo.SetValue(_parent, value);
            }
    
            private static string FormatPropertyName(string propertyName)
            {
                // get the first letter of the property name.
                var sb = new StringBuilder();
    
                sb.Append("_");
                sb.Append(char.ToLower(propertyName[0]));
                sb.Append(propertyName.Substring(1));
    
                return sb.ToString();
            }
    
            #endregion Methods
        }
    

    UPDATE – ADDED CODE FOR IPROPERTY SETTER THAT WAS MISSING

        public interface IPropertySetter<T>
        {
            #region Methods
    
            void SetValue(T value);
    
            #endregion Methods
        }