Unit Test Naming Convention

I’ve been writing tests and unit tests for quite a while, and naturally my personal preference for naming them has evolved somewhat with time.  Initially, I didn’t really know what I was doing and the default organization tended to be something like “given a class, Customer, all of the tests will go into a class called CustomerTests.”  This turned out, for me at least, to be less than ideal.  Later I learned more about BDD and specifications and I decided I could apply some of the same context and scenario information to my test organization as well.  Thus, I began striving to write my test classes such that each one described a particular scenario, and each test described a particular variation within that scenario (e.g. happy path, sad path, etc.).

By way of example, consider an e-commerce module that includes a pricing calculator.  One particular scenario for the pricing calculator might be to deal with a “preferred customer” who gets a special discount.  Others might be for regular customers, and still others for dealing with high volume orders or wholesale customers.  If I were to name my classes the way I did when I first started writing tests, I might have a PricingCalculatorTests class, which in turn would have many dozens of tests in it.  However, using my current preference, I might have classes like PricingCalculatorGivenNormalCustomerShould, PricingCalculatorGivenPreferredCustomerShould, PricingCalculatorGivenWholesaleCustomerShould, etc.  If I find that there are a great many such classes, then of course you can use namespaces and folders to keep things well organized.

When using this style of test naming, the Test View in Visual Studio becomes very easy to read.  Simply change the default Group By to Class Name (or if you are putting scenario information into your namespace, consider using Full Class Name).

image

Test results can be grouped similarly:

image

I’ve written up a small sample showing this naming convention – download the sample project here.  Below you can see one of the test classes in its entirety as well as the System Under Test, the Pricing Calculator.

PricingCalculatorGivenRegularCustomerShould.cs – Test Class

PricingCalculator.cs – System Under Test

Summary

If you’ve bought into the idea that testing actually helps to improve the quality of the software you build, and you’ve further realized that automated testing is far more cost effective than manual testing, then it follows that you will need to organize your tests in some fashion.  I have personally found the above technique to be useful in doing so on projects I work on.  I don’t suggest that this technique will work everywhere for everyone, or that it is the ultimate such technique (especially given that it’s only the latest in a series of different conventions I have adopted).  However, it remains my current favored approach because it produces easily understood tests whose classes tend to follow the Single Responsibility Principle and Open/Closed Principle, as well as producing output that is easily understood by everyone on the development team as well as by business stakeholders.

Update for 2016

I’ve been using this convention for a long time. One thing that I find useful now is to use more files and folders (and often fewer test projects). So, I might have a single test project, and within it folders relating to each of the project I might have tests for (e.g. Core, Infrastructure, Web). Even if I only have one project I’m testing, I’ll probably have folders in the test project corresponding to the folders in the project I’m testing (e.g. Model, Services, Exceptions, EventHandlers). Within the folder corresponding to where the class I’m testing lives, if the class has just one method worth testing, I’ll just create the ClassFooMethodBarShould.cs file there. However, if it has many methods, I’ll create a folder for the class, and put the individual method-based test classes within this folder. Here is the one instance where I deviate from my usual rule about not calling things “SomeClassTests” – I typically will use this for the foldername where the class’s test files are. The reason is simple: if I use the class name, and then use the class name as the namespace, it makes life difficult when trying to reference the class-under-test.

For example, say I have MyProject.Core.Entities.Customer that I want to test. I have a test project called MyProject.Tests. I’ll create folders Core and in it Entities. If Customer has only one method I’m testing, I’ll put CustomerDoSomethingShould.cs in the Entities folder. However, once I get a second method for Customer to test, I’ll create a folder CustomerTests, and put classes in that folder. At that point, I’ll also frequently drop the class name from test classes, since it’s in the namespace (more or less). The end result might be fully qualified test class names like:

MyProject.Tests.Core.Entities.CustomerTests.DoSomethingShould
MyProject.Tests.Core.Entities.CustomerTests.DoSomethingElseShould

etc.

  • Twitter Trackbacks for Unit Test Naming Convention: I???ve been writing tests and unit tests for quite a while, and naturally my

    Pingback from Twitter Trackbacks for Unit Test Naming Convention: I???ve been writing tests and unit tests for quite a while, and naturally my personal… [stevesmithblog.com] on Topsy.com

  • Smart Company Software

    Good information. Thanks.

  • Glenn

    Very nice organization. I am going to give this technique a go. It’ll solve some messiness in our code base.

  • Danie marbach

    Hy

    We use the following convention which works very well for us:

    Feature_precondition_postcondition

    I.e. savecustomer_whenexceptionoccurs_mustrollbacktransaction

    Or simple when no precondition available

    Savecustomer_mustusetransactionboundaries

    We use camel casing for the stuff between the underscores but I am too lazy to press shift on my ipad 🙂

    The cool about this get sorted together in the r# runner. And even on CI server they stay grouped together

    Daniel

    Daniel

  • film

    Good information. Thanks.

  • Friday Links #135 | Blue Onion Software *

    Pingback from Friday Links #135 | Blue Onion Software *

  • Prabir Shrestha

    Looks like a good way to organinge tests.

    currently i use

    methodname_stateundertest_expected behavior.

    I had actually return a small html page + js to allow be to write auto generate xunit.net method names.

    you can see the live method name generator at projects.prabir.me/…/UnitTestMethodG

  • Si

    I’m also a fan of the Member_PreCondition_PostCondition convention for naming unit tests.

    It’s interesting that you use the SRP as a reason for separating out your test classes, as one thing I’ve noticed is that if the number of unit tests in FooTests.cs gets too large, then it might be a hint I’m doing too much in the class. But as you say, horses for courses 🙂

  • Raj

    Nice post. You could also use ReSharper live templates to generate test method names. We use [Subject]_[Scenario]_[Result] for method names, and [ClassName]UnitTests for the class name.

  • Rodney Foley

    Steve, love the post and I have started using this method as much as I can. I was wondering your take on naming conventions on a method under test that returns void? After you tests the code paths that can throw exceptions you need to test the other paths of the method and you cannot use Return as a prefix to help.

  • Steve Smith

    @Rodney,

    What are you asserting for your void methods? That’s what you should say in your Should… test with my naming convention, typically. For instance, maybe you have a Create() method on a repository (let’s say for an Order). Then you might have a test fixture/class called OrderRepositoryCreateShould and then methods like ThrowExceptionGivenNullOrder() as a sad path and perhaps AddAnOrderGivenValidOrder() as a possible happy path. Or if it’s obvious from the name of the method what it should do, you can say ShouldSucceedGivenValidInput() or something similar. Hope that’s helpful.

  • Ivan Simich

    Good article Steve, thank you.

  • Sriram Sakthivel

    Thanks steve, You have educated me enough. I’ve got benefited by you from pluralsight courses too. I’ve seen some standards naming for unit testing. I really like your naming convention very much. What I’m missing is how will you organize the test when your class is having more than one method. Let’s say your Pricing calculator have two methods CalculatePrice and CalculateInterest. What will be the name of the test class and methods in that case?

  • ssmith

    Hi Sriram,

    I recommend having a separate test class per method being tested, honestly. If that means there are a lot of different classes, I either see that as a code smell (the class is doing to much, violates SRP, etc.) or I just create a folder for the class, and put the method-specific test classes into that folder (and namespace). In your example, I would likely have classes PricingCalculator_CalculatePriceShould and PricingCalculator_CalculateInterestShould. With just two I might not bother with a folder; with 3 or more I would typically add a folder (or consider refactoring the SUT).

  • ardalis

    Often when I’m just starting testing a method or class, I will just put the Given in the test name, so the class might be FooServiceDoSomethingShould and the method would be ReturnFooGivenBar. If the class has a lot of methods and/or different inputs, I might pull the Given up into the class, but with the support for TestCases in most testing frameworks, I can usually cover multiple Givens (inputs) easily in one test.

    Another optimization when this technique scales is to put all tests for a given class in a folder. At that point, using standard namespace conventions, the SUT class’s name will be in the namespace, and so it doesn’t need to be repeated in the class name. Then the namespace in the example above would end with FooService, and the class would be DoSomethingShould.