Don’t jump the red light!

Posted by Graeme | Posted in Development | Posted on 15-02-2010

1

There’s a good reason why the test-driven development cycle says you should always watch a test fail before you write the production code that makes it pass. I was taught a lesson in this today, “school of hard knocks” style…

How did it happen?

I have a simple class which implements INotifyPropertyChanged and has property:

public class MyClass : INotifyPropertyChanged
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Name"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

To test that the PropertyChanged event is raised at the appropriate time I use Caliburn’s handy (and very readable) PropertyHasChangedAssertion:

[TestFixture]
public class MyClassTestFixture
{
    [Test]
    public void Name_WhenSet_RaisesPropertyChanged()
    {
        var test = new MyClass();

        test.AssertThatChangeNotificationIsRaisedBy(x => x.Name);
    }
}

At the time I obviously thought this was too simple to worry about, saw the test passed as expected and moved on. All good… Or so it seemed!

Fast forward a week or two. I started to get some strange errors – not test failures – in my MSBuild output:

error : Internal error: An unhandled exception occurred.

error : System.Exception: No context was provided to test the notification, use When(Action affectProperty) to provide a context.

error :    at Caliburn.Testability.Assertions.PropertyHasChangedAssertion`2.Finalize()

Not only is the message a bit cryptic without any context (e.g. a test) but the error was intermittent. Oh joy! After a bit of detective work (more than you might think!) I realised that this is because the Caliburn’s PropertyHasChangedAssertion checks that you called its When(Action affectProperty) method in its finalizer:

~PropertyHasChangedAssertion()
{
    if(!_isValidAssertion)
        throw new Exception(
            "No context was provided to test the notification, use When(Action affectProperty) to provide a context.");
}

While this makes the test extremely readable (which is, of course, extremely important), if you forget to call When(), if and when you get an error is up to the non-deterministic finalization gods. An easy one to fix:

[Test]
public void Name_WhenSet_RaisesPropertyChanged()
{
    var test = new MyClass();

    test.AssertThatChangeNotificationIsRaisedBy(x => x.Name)
        .When(() => test.Name = "New name");
}

But I didn’t get the feedback that I should have done from doing TDD properly, and wasted time as a result.

What went wrong?

Here is how TDD is supposed to be performed:

Because the code was trivial, I skipped the second step and didn’t check that the test failed before I carried on and implemented the property. If I hadn’t skipped this step, there’s a good chance that the following sequence of events would have occurred:

  1. I write the test, and add an empty property definition to make it compile
  2. I run the test and see that it unexpectedly passes
  3. I scratch my head for a bit, but I’m already looking at the offending line of code so it’s much easier to spot the problem
  4. The penny drops, I spot the mistake and fix it
  5. I run the test again, and this time it fails. Happy days.
  6. I implement the property changed notification and carry on

Maybe I would have got the error when I ran the test, and that would have given me another clue about the cause of the problem.

It could have been worse!

In the week or two since I made the mistake I could have carried on to use AssertThatChangeNotificationIsRaisedBy in tens or hundreds of other tests, which would have made it much harder to find the one with the missing When() call. I was lucky that there were only a few uses in my tests.

A lesson learned?

I hope so! When time is short it can be hard to make yourself go through these steps over and over again, but they are all there for a reason – to stop us writing code that doesn’t do what we think it does. I will be trying especially hard to stick to the steps, but we’ll have to wait and see how it goes.

How I’m Growing Object-Oriented Software, Guided by Tests

Posted by Graeme | Posted in Development | Posted on 08-02-2010

6


Growing Object-Oriented Software, Guided by Tests (that’s #goos on Twitter) by Steve Freeman and Nat Pryce is a book about test-driven development. Here are a few notes on my experiences of following its methods.

The Story So Far

I was fortunate enough to start work on a new desktop application in the middle of last year, around the time I read through the freely-available online version of the book before it was finally published in November. This was an ideal opportunity to put TDD into practice so I started by building a “walking skeleton” using Prism, CruiseControl.NET, WiX, Gallio, MbUnit, NCover and White as a wrapper around UI Automation for the acceptance tests, and took it from there.

I’ll admit that there was a slow start (WPF/Prism and White/UI Automation were new to me too) but development speed has been steadily increasing ever since, and now I’m able to get what feels like a lot done each day. And that’s pretty much every day; it’s been a long time since I’ve had to halt progress for a significant amount of time in order to squash a bug or redo a chunk of work.

Where am I now?

I’m still learning. It’s easy to slip back into changing code then updating the tests to match, and I do find myself doing that sometimes. I’m also finding it hard to perform only one refactoring step at a time (oh, let me just rename that class while I’m here…), and the acceptance tests can be brittle and sometimes feel like a burden to write. But what doesn’t kill you makes you stronger, right? It’s getting noticeably easier as I learn and improve, and every bit of pain along the way has been worth it.

Does it work?

For me, yes. Test-driven development feels so right that I don’t think I could ever go back to hacking stuff together without building the safety net of tests to fall back on as I go. I am sure that my design is much better than anything I have produced before, and that I have far fewer bugs than usual, too :)

So this experience has been nothing short of (professional) life-changing. I have read similar stuff before, but GOOS was the one that finally made me “get it.”

Hello again, World!

Posted by Graeme | Posted in meta | Posted on 06-02-2010

1

GraemeF.com has been around in one form or another since 2001, but I had a poke around the blog content and decided that each bit fell into one or more of the following categories:

  1. Outdated technical posts that would be downright misleading now;
  2. Personal stuff that the Interwebs should not be interested in;
  3. Links auto-posted from my Del.icio.us account;
  4. Factually inaccurate bullshit.

So, rather than actually create categories for the above, I decided to reboot my blog, and now all of the old content is gone.

So what now?

It’s time for a fresh start. Having dabbled with product management for a while and ultimately decided that it’s not for me, I’m back to being a full-time software developer, and that’s what I intend to write about.

However, what’s more likely to happen is:

  1. I start off well, with a couple of posts about test driven development and the like;
  2. The posts get shorter and shorter and are spaced farther and farther apart;
  3. In a year’s time I’ve all but forgotten about it when the hosting charge is applied to my debit card, for which my wife never forgives me.

Sounds like a plan! :)