TheJoyOfCode.QualityTools.ConstructorTester

The QualityTools library can also help you test your constructors thanks to the ConstructorTester. 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;    
    }

    public string Name { get; set; }
    public string DateOfBirth { get; set; }


[Test]
public void TestPersonConstructors()
{
    ConstructorTester tester = new ConstructorTester(typeof(Person));
    tester.TestConstructors(false);
}


This static method will test all constructors available on the object by creating random values using the TypeFactory (follow the link for supported types). Obviously, in this basic example no logic is validated the constructor is just called and if no exception is raised your test will pass.

Mapped properties.

The TestConstructors method has a testMappedProperties parameter which, if set to true, will test that any properties on the new object that have a namesake on the constructor (case insensitive matching) have the same value that was injected at construction.

[Test]
public void TestPersonConstructors()
{
    ConstructorTester tester = new ConstructorTester(typeof(Person));
    tester.TestConstructors(true);
}


In this case our test will fail because our example object above takes a dateOfBirth parameter at construction and has a DateOfBirth property but this property is never wired up. The resulting ConstructorTestException would have the following message: "The value of the 'DateOfBirth' property did not equal the value set with the 'dateOfBirth' constructor parameter (in: '2007-09-22', out: '1900-01-01')"

Exclusions

Again, if there are some constructors that you need to skip over because they have some funky logic you can add them to a blacklist. Maybe you have to blacklist a particular constructor because it takes a parameter that the TypeFactory can't create.

[Test]
public void TestPersonConstructors()
{
    ConstructorTester tester = new ConstructorTester(typeof(Person));
    // we specify the signature of the constructor to be ignored
    tester.IgnoredConstructors.Add(typeof(string), typeof(ISomeInterface), typeof(object));
    tester.TestConstructors(true);
}

Last edited Jan 4, 2008 at 12:57 PM by molmorg, version 1

Comments

No comments yet.