Unit tests naming guidelines
Basic set of guidelines I follow when naming unit test method:
1. Use long, descriptive names
Don’t be afraid to use long names. And I’m talking really long. Since unit tests are not part of public API (nor any API in fact), how test method is named is irrelevant in the context of its usage (as it won’t ever be used in traditional sense). Important thing here is - name of test should be enough to give reader the idea of what’s being tested.
Few examples of rather poor test names (can you tell what those tests do?):
Test16(I noticed those are common when people are forced to write tests; usually combined with testing many things at once and overall poor test code quality),
SaveNoException(clearly author attempted to put some effort into the naming process but it’s still too vague)
Good names, on the other hand:
2. Prefer descriptive name rather than documentation
As long as documenting your code is important, once again it makes most sense with API parts. Unit test is not an API. Documentation doesn’t show up in test runners. Method name does. It’s as simple as that.
3. Stay consistent with naming approach you use
There are many decent test method naming templates, and as long as test name gives enough information it doesn’t make much difference which approach you choose, given it’s the same one throughout the project. Personally, I use slightly modified version of the one proposed by Roy Osherove with minor improvement stolen from Jon Skeet:
TestedMethodName_ExpectedBehavior_StateUnderTest- Roy’s version has
TestedMethodName_ExpectedBehavior- conditions here would be something along the lines of “when nothing special happens” or “when everything else works as expected”, so I decided to skip them as they add no extra information - Jon Skeet’s improvement (although I can’t seem to find source for that).
The reason for switching
StateUnderTest is very simple; it feels more natural and reads out in nice, narrative form (this might naturally vary from language to language [spoken, not programming :-)]; in my native language that’s how sentences are usually structured). For example:
Those names read exactly as a sentence you might say when describing the test (or rather method’s behavior under given circumstances) to other person.
Finally, it’s good to be aware there’re more common templates, including:
TestedMethodName_StateUnderTest_ExpectedBehavior- Roy’s original one,
StateUnderTestTestedMethodNameExpectedResult- no underscores at all; I found it quite confusing/more difficult to figure out when longer names were involved (and it might get kind of silly/repetitive with stuff like
TestMethodName_State_Under_Test_Expected_Behavior- underscore between each english word except for tested method name. I find it quite messy once again when longer names are involved.
That’s about it when it comes to test method naming.