646
votes

What are the best practices for naming unit test classes and test methods?

This was discussed on SO before, at What are some popular naming conventions for Unit Tests?

I don't know if this is a very good approach, but currently in my testing projects, I have one-to-one mappings between each production class and a test class, e.g. Product and ProductTest.

In my test classes I then have methods with the names of the methods I am testing, an underscore, and then the situation and what I expect to happen, e.g. Save_ShouldThrowExceptionWithNullName().

4

11 Answers 11

606
votes

Update (Jul 2021)

It's been quite a while since my original answer (almost 12 years) and best practices have been changing a lot during this time. So I feel inclined to update my own answer and offer different naming strategies to the readers.

Many comments and answers point out that the naming strategy I propose in my original answer is not resistant to refactorings and ends up with difficult to understand names, and I fully agree.

In the last years, I ended up using a more human readable naming schema where the test name describes what we want to test, in the line described by Vladimir Khorikov.

Some examples would be:

  • Add_credit_updates_customer_balance
  • Purchase_without_funds_is_not_possible
  • Add_affiliate_discount

But as you can see it's quite a flexible schema but the most important thing is that reading the name you know what the test is about without including technical details that may change over time.

To name the projects and test classes I still adhere to the original answer schema.

Original answer (Oct 2009)

I like Roy Osherove's naming strategy. It's the following:

[UnitOfWork_StateUnderTest_ExpectedBehavior]

It has every information needed on the method name and in a structured manner.

The unit of work can be as small as a single method, a class, or as large as multiple classes. It should represent all the things that are to be tested in this test case and are under control.

For assemblies, I use the typical .Tests ending, which I think is quite widespread and the same for classes (ending with Tests):

[NameOfTheClassUnderTestTests]

Previously, I used Fixture as suffix instead of Tests, but I think the latter is more common, then I changed the naming strategy.

19
  • 258
    For me it makes no sense to put method name in test method. What if You rename method? No refactoring tool will rename tests for You. Eventually You end up renaming test methods by hand or more likely having wrongly named tests. It's like with comments. To much is worse then not commenting code at all. Commented May 29, 2011 at 5:41
  • 96
    @Peri, I think it is a tradeoff. On one hand your test names may become outdated, on the other hand you can't tell what method your test is testing. I find the latter comes up much more often. Commented Apr 19, 2012 at 19:23
  • 17
    To add to Peri's comment - all methods are responsible for some action, e.g UpdateManager.Update(). Having this in mind I tend to call my tests WhenUpdating_State_Behaviour or WhenUpdating_Behaviour_State. This way I test a particular action of a class while avoiding to put a method name in a test name. But the most important thing is that I have to have a clue what business logic is failing when I see a name of a failing test
    – Ramunas
    Commented Oct 25, 2012 at 6:19
  • 9
    Resharper and IntelliJ both would probably find your test method and offer to rename it for you if you refactored/renamed using those tools. The also try to look in comments where you mention the method name and update those too. Commented Dec 6, 2012 at 14:50
  • 70
    Good method names often are the same as the action the method perfoms. If you have to decide between naming your test after your method or the action the method performs that may be a hint you should rename your method. (Not in every case though)
    – Kaadzia
    Commented Sep 19, 2013 at 9:04
151
votes

I like to follow the "Should" naming standard for tests while naming the test fixture after the unit under test (i.e. the class).

To illustrate (using C# and NUnit):

[TestFixture]
public class BankAccountTests
{
  [Test]
  public void Should_Increase_Balance_When_Deposit_Is_Made()
  {
     var bankAccount = new BankAccount();
     bankAccount.Deposit(100);
     Assert.That(bankAccount.Balance, Is.EqualTo(100));
  }
}

Why "Should"?

I find that it forces the test writers to name the test with a sentence along the lines of "Should [be in some state] [after/before/when] [action takes place]"

Yes, writing "Should" everywhere does get a bit repetitive, but as I said it forces writers to think in the correct way (so can be good for novices). Plus it generally results in a readable English test name.

Update:

I've noticed that Jimmy Bogard is also a fan of 'should' and even has a unit test library called Should.

Update (4 years later...)

For those interested, my approach to naming tests has evolved over the years. One of the issues with the Should pattern I describe above as its not easy to know at a glance which method is under test. For OOP I think it makes more sense to start the test name with the method under test. For a well designed class this should result in readable test method names. I now use a format similar to <method>_Should<expected>_When<condition>. Obviously depending on the context you may want to substitute the Should/When verbs for something more appropriate. Example: Deposit_ShouldIncreaseBalance_WhenGivenPositiveValue()

8
  • 46
    Maybe even better and less redundant, just write a sentence that tells what it does, assuming the test works: increasesBalanceWhenDepositIsMade().
    – hotshot309
    Commented Feb 9, 2012 at 22:17
  • 3
    Recently saw an article that mentioned a similar naming convention (wish I'd bookmarked it). Designed to make the lists of tests very readable when sorted by test fixture. You see something like "BankAccount" then under it (on different lines) "Should_Increase_Balance_When_Deposit_Is_Made" "Should_Decrease_Balance_When_Withdrawal_Is_Made", etc. Reads very like a specification, which is sort of what TDD is all about.
    – Simon Elms
    Commented Jan 22, 2013 at 0:00
  • Found the article. It's in Justin Etheredge's CodeThinked blog Beginning Mocking With Moq 3 – Part 1.
    – Simon Elms
    Commented Jan 22, 2013 at 0:48
  • 13
    I also use Should and When but the other way round. e.g. WhenCustomerDoesNotExist_ShouldThrowException(). To me this makes a lot more sense than Should then When (i.e in a certain scenario there should be a certain expected outcome). This also fits in with AAA (Arrange, Act, Assert)...the Assert is at the end...not the beginning ;-)
    – bytedev
    Commented Apr 15, 2015 at 14:38
  • 2
    @Schneider : considering "should" = "recommended" then optional, I wonder: would not it be lexicaly better to use "shall" = "must" then required/mandatory. For example, RFCs makes the difference between both. So having tests pass is recommended or required? Commented Jun 7, 2017 at 8:51
89
votes

I like this naming style:

OrdersShouldBeCreated();
OrdersWithNoProductsShouldFail();

and so on. It makes really clear to a non-tester what the problem is.

8
  • 64
    but @hotshot309, he may be using .NET - .NET Capitalization Conventions
    – Ace
    Commented Mar 9, 2012 at 15:21
  • 2
    @Ace, I totally agree with you and noticed this about a minute after I posted this comment. I swore that I deleted it when I saw my mistake, but somehow, I guess I didn't. Sorry about that.
    – hotshot309
    Commented Mar 13, 2012 at 16:08
  • 3
    @CoffeeAddict because underscores within identifiers are an <del>aberration</del> not really idiomatic in C#
    – Sklivvz
    Commented Oct 24, 2013 at 10:10
  • 2
    I also like to avoid the usage of should I will prefer will so OrdersWithNoProductsWillFail()
    – Calin
    Commented Feb 13, 2015 at 10:08
  • 6
    @Calin In my opinion using Will isn't really appropriate and by doing so you're actually mistakenly telling the reader that in no way the test will fail... if you use Will to express something in the future that might not happen you're using it incorrectly whereas Should is the better choice here because it indicates that you want/wish something to happen but it didn't or couldn't, when the test runs it tells you whether it failed/succeeded so you can't really imply that beforehand, that's the logical explanation to it, what's yours? why do you avoid Should?
    – iam3yal
    Commented Oct 10, 2016 at 4:24
56
votes

Kent Beck suggests:

  • One test fixture per 'unit' (class of your program). Test fixtures are classes themselves. The test fixture name should be:

    [name of your 'unit']Tests
    
  • Test cases (the test fixture methods) have names like:

    test[feature being tested]
    

For example, having the following class:

class Person {
    int calculateAge() { ... }

    // other methods and properties
}

A test fixture would be:

class PersonTests {

    testAgeCalculationWithNoBirthDate() { ... }

    // or

    testCalculateAge() { ... }
}
7
  • 5
    I wish more people would follow these guidelines. Not too long ago I had to rename more than 20 test methods because they had names like "ATest", "BasicTest", or "ErrorTest".
    – Wedge
    Commented Sep 30, 2008 at 23:44
  • 91
    doesn't the method prefix of 'test' become redundant given the class's suffix? Commented Jan 5, 2009 at 21:12
  • 55
    Remember that when Kent wrote that book. Attributes was not invented. Therefore the name Test in the method name indicated to the test framework that the method was a test. Also alot have happend since 2002. Commented May 15, 2010 at 16:04
  • 14
    testCalculateAge... this is a meaningless name for your test method. "test" is redundant (do you name all your methods with "method" prefix?). The rest of the name has no condition under test or what was expected. Is CalculateAge the method under test?.....who knows...
    – bytedev
    Commented Feb 27, 2013 at 14:02
  • 1
    I'd like to add that when using this strategy, documentation is required to specify the expected output. As a side note about the 'test' prefix; some unit testing frameworks require specific prefixes or suffixes to recognize the tests. Prefixing abstract classes with 'Abstract' is not considered redundant (because it's self documenting), so why doesn't the same apply with 'Test'?
    – siebz0r
    Commented Aug 3, 2013 at 8:44
19
votes

Class Names. For test fixture names, I find that "Test" is quite common in the ubiquitous language of many domains. For example, in an engineering domain: StressTest, and in a cosmetics domain: SkinTest. Sorry to disagree with Kent, but using "Test" in my test fixtures (StressTestTest?) is confusing.

"Unit" is also used a lot in domains. E.g. MeasurementUnit. Is a class called MeasurementUnitTest a test of "Measurement" or "MeasurementUnit"?

Therefore I like to use the "Qa" prefix for all my test classes. E.g. QaSkinTest and QaMeasurementUnit. It is never confused with domain objects, and using a prefix rather than a suffix means that all the test fixtures live together visually (useful if you have fakes or other support classes in your test project)

Namespaces. I work in C# and I keep my test classes in the same namespace as the class they are testing. It is more convenient than having separate test namespaces. Of course, the test classes are in a different project.

Test method names. I like to name my methods WhenXXX_ExpectYYY. It makes the precondition clear, and helps with automated documentation (a la TestDox). This is similar to the advice on the Google testing blog, but with more separation of preconditions and expectations. For example:

WhenDivisorIsNonZero_ExpectDivisionResult
WhenDivisorIsZero_ExpectError
WhenInventoryIsBelowOrderQty_ExpectBackOrder
WhenInventoryIsAboveOrderQty_ExpectReducedInventory
1
  • you talked about test method names and test fixture names. test fixture names are mapped to production classes. where do you write the production method name in your test?
    – The Light
    Commented May 28, 2011 at 17:23
14
votes

I use Given-When-Then concept. Take a look at this short article http://cakebaker.42dh.com/2009/05/28/given-when-then/. Article describes this concept in terms of BDD, but you can use it in TDD as well without any changes.

5
  • Given-When-Then is the same as MethodName_Scenario_ExpectedBehavior, isn't it?!
    – The Light
    Commented May 28, 2011 at 17:26
  • 2
    Not exactly. Given_When_Then refers more to: GivenAnEntity_WhenSomeActionHappens_ThatResultIsExpected The test should express the will to test a behavior not an implementation.
    – plog17
    Commented Oct 21, 2015 at 12:13
  • 1
    "Given When Then" is often refered to as Gherkin. Its a DSL that came out of the Cucumber, JBehave and Behat tools.
    – bytedev
    Commented Mar 30, 2016 at 15:48
  • +1 this is the best method imo. Decoupling how a method does something from what you expect the result to be is very powerful and avoids a lot of problems described in other comments.
    – Lee
    Commented Jan 16, 2019 at 14:40
  • Is it something like this? GivenLoggedIn_WhenWritingArticle_ThenShowSuccessMessage
    – wonsuc
    Commented Oct 19, 2020 at 5:42
10
votes

I recently came up with the following convention for naming my tests, their classes and containing projects in order to maximize their descriptivenes:

Lets say I am testing the Settings class in a project in the MyApp.Serialization namespace.

First I will create a test project with the MyApp.Serialization.Tests namespace.

Within this project and of course the namespace I will create a class called IfSettings (saved as IfSettings.cs).

Lets say I am testing the SaveStrings() method. -> I will name the test CanSaveStrings().

When I run this test it will show the following heading:

MyApp.Serialization.Tests.IfSettings.CanSaveStrings

I think this tells me very well, what it is testing.

Of course it is usefull that in English the noun "Tests" is the same as the verb "tests".

There is no limit to your creativity in naming the tests, so that we get full sentence headings for them.

Usually the Test names will have to start with a verb.

Examples include:

  • Detects (e.g. DetectsInvalidUserInput)
  • Throws (e.g. ThrowsOnNotFound)
  • Will (e.g. WillCloseTheDatabaseAfterTheTransaction)

etc.

Another option is to use "that" instead of "if".

The latter saves me keystrokes though and describes more exactly what I am doing, since I don't know, that the tested behavior is present, but am testing if it is.

[Edit]

After using above naming convention for a little longer now, I have found, that the If prefix can be confusing, when working with interfaces. It just so happens, that the testing class IfSerializer.cs looks very similar to the interface ISerializer.cs in the "Open Files Tab". This can get very annoying when switching back and forth between the tests, the class being tested and its interface. As a result I would now choose That over If as a prefix.

Additionally I now use - only for methods in my test classes as it is not considered best practice anywhere else - the "_" to separate words in my test method names as in:

[Test] public void detects_invalid_User_Input()

I find this to be easier to read.

[End Edit]

I hope this spawns some more ideas, since I consider naming tests of great importance as it can save you a lot of time that would otherwise have been spent trying to understand what the tests are doing (e.g. after resuming a project after an extended hiatus).

9
votes

See: http://googletesting.blogspot.com/2007/02/tott-naming-unit-tests-responsibly.html

For test method names, I personally find using verbose and self-documented names very useful (alongside Javadoc comments that further explain what the test is doing).

7
votes

I think one of the most important things is be consistent in your naming convention (and agree it with other members of your team). To many times I see loads of different conventions used in the same project.

2
votes

In VS + NUnit I usually create folders in my project to group functional tests together. Then I create unit test fixture classes and name them after the type of functionality I'm testing. The [Test] methods are named along the lines of Can_add_user_to_domain:

- MyUnitTestProject   
  + FTPServerTests <- Folder
   + UserManagerTests <- Test Fixture Class
     - Can_add_user_to_domain  <- Test methods
     - Can_delete_user_from_domain
     - Can_reset_password
2
votes

I should add that the keeping your tests in the same package but in a parallel directory to the source being tested eliminates the bloat of the code once your ready to deploy it without having to do a bunch of exclude patterns.

I personally like the best practices described in "JUnit Pocket Guide" ... it's hard to beat a book written by the co-author of JUnit!

1
  • 3
    Don't believe this actually answers the question at hand - could you make an edit and refrence JUnit Pocket Guide? Thanks! Commented Apr 17, 2014 at 15:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.