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.
Perhaps if you don’t know how you want the code to behave, then you haven’t thought through the design of your story enough. If find if you test the behaviour, rather than what it is meant to do, then you usually know what you want to happen. Sometimes, I decide to push implementation down to other services, helpers, or lower down the stack, but I keep the original test inplace, and also have the test at the required unit level.
Of course, there are always going to be those times when you really don’t know how the code will hang together. Pat Kua call these times experimentation http://www.thekua.com/atwork/2008/02/05/if-you-do-test-driven-development-all-the-time-youre-doing-something-wrong/. Take his advice – use TDD when you are focused on the problem, and know how to solve it; use experimentation to find out how to solve it (and then quite possible, revert all your changes and begin TDD)
I agree with Sarah. What I’ve found is that my unit test names are primarily driven by the story requirements. I extensively use the “Should…” paradigm to make sure I (and my pair) focus on the why, and not what or how. This way, the names tend to stay the same because I am implementing tests to confirm requirements are satisfied, and leave the implementation details to the code.