snappyco.de

rss

Assert Awesomely

I've been working on nicer test code and error messages. Here's what I started with:

var steve = new Zombie();
Assert.That(steve.Mood, Is.EqualTo("I'm hungry for brains!"));

Which tells me

Expected string length 22 but was 27. Strings differ at index 1.
Expected: "I'm hungry for brains!"
But was:  "I want to shuffle aimlessly"
------------^

That's crap!

What I really wanted was a short behaviour style test and an error message that told me steve's mood was not what I expected it to be.

First the test syntax can be fixed with an extension method:

public static void ShouldBe<T>(this T actual, T expected)
{
    actual.AssertAwesomely(Is.EqualTo(expected), expected);
}

The test:

var steve = new Zombie();
steve.Mood.ShouldBe("I'm hungry for brains!");

Nice!

Now on to the error message. I did some experimenting with c#'s reflection and stack trace api and turned up the file and line number of the test that went kaboom! I then applied some loose morals and sweet regular expressions to turn the error into this:

steve.Mood 
    should be 
        "I'm hungry for brains!" 
    but was 
        "I want to shuffle aimlessly"

Not bad if I do say so myself.

And here's the code (Feel free to fork and improve). http://gist.github.com/252084

I'm a sydney based software developer. I currently build stuff with ruby, c# and objective-c.

dave@snappyco.de

I'm on Twitter

  • Thanks japan, now I REALLY hate Sydney trains. 9 minute wait?!
  • Drugs are bad mmmkay http://bit.ly/9Jl7v1
  • NSCoders: [[NSArray arrayWithObjects:...] retain] or [[NSArray alloc] initWithObjects:...]
  • Anyone wanna give me a desk to work at today in surry hills?
  • Back in oz after a wicked japan #rubykaigi trip. Domo arigato japan!

I'm on Github