Archive for the 'Test Driven Development' Category

Naming unit tests

Sarah Taraporewalla has given some advice on naming tests on her blog,

My biggest problem with test names is that they may be perfectly fine when you write the code for the first time, but then…someone starts refactoring the code base. Tests start failing…and you fix the failing test…but not the test name.

My take home advice – think about what your test is doing before you begin to write the test. Perhaps you even write the names for 4 tests at once, before implementing any of them. That way you can focus on the test at hand, you don’t have to be thinking of testing a whole variety of cases in the one test and your tests become small enough that you can easily identify when the test name differs from the test at hand.

I completely agree with her, except in those instances where I am not sure what it is I am testing.

One habit that I picked up on my last project was naming a test after I had written it. While creating the unit test, I would simply name it foo(). Then, once I saw what the code was actually doing, I would go back and rename the test to something appropriate.

I find that names can get out of sync the code incredibly quickly. You create a name and by the time you finish writing the test, the code is testing something else. This is where naming tests after can be an advantage.

I am not sure if this highlights a deficiency in my understanding and implementation of TDD, but I find that even if I think about what I am testing before writing the test, the final unit test reflects something different. My understanding of what needs to be tested evolves right along with the code. And hence, writing test names after results in better test names.