Home > View Post

Testing Constructors with the ClassTester

UPDATE: This library has now been updated and moved to codeplex: details here.

Yesterday I introduced the ClassTester in the post entitled Automatically Unit Test your Model.

The ClassTester can also help you test your constructors. It's a very common practice to create a custom constructor to help inject property values at construction time. Like this:

public class Person
{
    public Person(string name, DateTime dateOfBirth)
    {
        _name = name;    
    }
    
    // etc

I actually noted in a recent post how I prefer this pattern over the new Object Initializers coming in C# 3.0 - agreeing with Bruusi's thoughts in his post Initialisation using constructors.
The sharp eyed will have noticed that I forgot to wire up the dateOfBirth parameter - easily missed but could be a sticky bug to track down. The ClassTester can help you here too.

[Test]
public void TestPersonConstructors()
{
    ClassTester.TestConstructors(typeof(Person), true);
}

This static method will test all constructors available on the object by creating random values for each parameter. If one of your constructors has a lot of funky logic here then I'm afraid you're back to manual tests (an obvious feature here would be to be able to specify individual constructors to ignore, that's not in there yet).

If the second parameter is passed as true to the TestConstrctors method, it will also inspect 'mapped' properties to make sure they have the same value as that passed into the constructor. It does this by looking for properties with the same name as the parameter (ignoring case).

There are many limitations to this but I think it probably fits for most constructors in simple POCO scenarios.

Once more, this should improve your code coverage as it's often those overloaded constructors that are left untested.

Tags: .NET

 
Josh Post By Josh Twist
2:57 AM
04 Aug 2007

» Next Post: Dedicated thread or a ThreadPool thread. Or a Custom ThreadPool thread
« Previous Post: Automatically Unit Test your Model

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.