How to Name Test Methods
I really like BDD (Behavior Driven Development) and it’s structure for helping to focus on behavior instead of implementation when you write unit tests. Some time ago I ran across a blog post by my former colleague in the patterns & practices group Daniel Cazzulino: Writing meaningful, self-documenting, behavior-oriented tests. Another good post, which has more links to BDD is this one: Approaching Behavior Driven Development (BDD) from a Test Driven Development (TDD) perspective.
As a result, I started naming my tests with names like this, using underscores to separate the different BDD keywords:
[TestMethod]
[Description("Column order is different, but tables match")]
public void ShouldNotThrow_WhenAreEqual_GivenSameData_ButColumnOrderDifferent()
This worked reasonably well in Visual Studio 2010 tests results window because I could show the Description column. That way the test results included an easy to read description (the Description attribute), as well as the Given/When/Then behind the test (although I put the Then part first and called it Should):
Then along came Dev11 beta. They’ve completely changed the test results experience. The new version, at least in the beta, doesn’t support the description attribute, so you only see the test method names, resulting in my test results looking like this:
Argh! That makes it really hard to read test methods. Plus, I wasn’t completely happy with the long test methods anyway. What to do?
Rethinking Test Method Naming
I had a nice conversation with another former p&p colleague, Peter Provost, who is a PM working on the test experience. He suggested that I put the BDD description into the Description attribute. I decided to try this out, and so far I’m liking the change:
// Column order is different, but tables match
[TestMethod]
[Description("Given two tables And same data But different column order | When TableAssert | Then true")]
public void ColumnOrderDoesntMatter()
Here is what this looks like in the new test runner:
One nice thing about this approach is that the BDD description is easier to read and it can be richer without overwhelming the method name.
Wishful Thinking
I think it would be really cool (just my opinion) if this had a rich tooltip that showed the class information (the current tooltop does) and also the Description attribute. It would also be really cool if I could write an VS extension that would format my descriptions into multiple lines with keywords like Given, When, and Then in bold. Hint, hint VS guys…