jimmy keen

on .NET, C# and unit testing

Unit tests naming guidelines

April 16, 2012 | tags: unit-testing 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?):

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:

The reason for switching ExpectedBehavior with 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:

That’s about it when it comes to test method naming.