Named Parameters and Unit Testing

22. January 2010 Howto 0

I’m a bit of what you might call a “late adopter.” I run from ‘bleeding edge technology.’ I finally upgraded from XP-SP2 about a month ago (made the jump to W7.) Just upgraded It’s Greek To Me from VB5 & Access to .Net 3.5 & SQL Compact. And I’m finally getting around to using .Net 3.5 regularly, now that 4.0 is about to come out.

All that said, I wish I could have upgraded earlier, but some business reasons kept me from doing so.

As I’m writing this, I’m in the middle of writing some unit tests, and that highlights one of my “new” favorite features — Named Parameters.

For the un-initiated (and really, if you haven’t adopted yet, what ARE you doing?) C# constructors are usually called like:

Book b = new Book("Jonathan Edwards", "Religious Affections", 1746);

But with Named Parameters, I could do:

Book b = new Book{Title = "Religious Affections"};

Why is this great? Because now when I’m unit testing something, I don’t have to type in every parameter under the sun, just to test the case where 1 is null.

So I can have a test case that might look like

[ExpectedException(typeof(InvalidAuthorException))]
public void GetPrice_NoTitle_ShouldThrowException()
{
    Book b = new Book{Title = "Religious Affections", Year = 1746};
    b.GetPrice();
}

This might not be the best example, since I could have easily put Book(null, “Religous Affections”, 1746), but I think it is illustrative enough.


Leave a Reply

Your email address will not be published. Required fields are marked *