Wednesday 14 September 2011

TDD day with Roy Osherove

Had a great TDD (and unit test) course with Roy Osherove at my company yesterday.
Here are some things that caught my attention. I'm writing them down mainly for a reminder to myself.
1. Good test names
Good test names are everything! There is nothing wrong with that it may take hours(!) just to come up with a good name for the test. Don't start writing code for the test and make up a name for it later - spend time on the name instead! If you have a great name, writing the code for it will take minutes.
2. Refactor tests
This may sound obvious, but you often forget that even your tests needs refractoring. A test should only contain a couple of lines of code. It it doesn't it's a signal that you are writing a bad test. Maybe you're testing the wrong thing or testing to much or anything else. To help: see 1). ...or refactor!
3. No [SetUp]
Don't use setup. It destroys readability. Refractor instead. More reading: http://jamesnewkirk.typepad.com/posts/2007/09/why-you-should-.html
4. No [TearDown]
It's fine to use teardowns. But it's a signal that you are not writing unit tests, you are writing integration tests!

Maybe I'll update this post if I start to remember more things :-)

2 comments:

  1. I agree that naming is crucial. But I don't agree that Setup is bad. If you have big test classes with lots of test and a setup method with initialization code for all tests, then you have a big mess. A better idea is to have smaller test classes and not one test class per prod class. I like the style that Scott Bellware advocates in his blog post:
    http://codebetter.com/scottbellware/2007/09/22/setup-and-teardown-methods-in-test-classes/

    ReplyDelete
  2. pwigle: it's not really my own opinions, but anyway I'm defending Roy here :-)
    You can always refactor your tests with the same result as a SetUp (in fact it's kind of the same thing). The only thing you get with SetUp is bad readability; if someone else reads your test they will wonder "Hey! Where does the 't' variable come from?" and he/she will have to look in the SetUp to know. It's much more readable to call a method - you instantly know where things comes from.

    Example
    This:

    TheThing thing = CreateADefaultThing()
    bool hmmm = thing.DoYourThing();

    Or this:

    bool hmmm = thing.DoYourThing(): // What's thing? Where does it come from?

    ReplyDelete