Skip to content

Naming unittest

Thomas Volden edited this page Feb 15, 2019 · 2 revisions

tl;dr Name your tests like this:
[method]_[scenario]_[behavior]

Inspired/taken from the book The art of unittesting.

Conventions for unit test names, makes it easier to read and understand what a test does.

The test name has three parts:

  • The name of the method being tested.
  • The scenario under which it's being tested.
  • The expected behavior when the scenario is invoked.

The goal is to write test names, that a coder can understand without looking at the code first.

The common way to write these names, are to seperate them with underscores.
Example: MethodUnderTest_Scenario_Behavior()

Here is a modified example from the book The art of unittesting:

@Test
public void AnalyzeFile_FileWith3LinesAndFileProvider_CallsReadFileOnProvider() {
    // ...
}

This tests the method AnalyzeFile giving it a file with three lines and a file-reading provider, and it expects it to use the provider to read the file.

Method

This is the most import part of the name. It helps the reader to locate where the logic is placed. If your test fails, this part tells you exactly where to focus.

Scenario

The scenario part, tells the reader what the state of the system is. It's tempting to skip the scenario part in tests that doesn't setup the state of the system. Instead of skipping it, you should tell the reader, that the system is in default state. Here are some scenario names you can use:

  • ByDefault
  • WhenCalled
  • Always

Behavior

There is 4 types of behavior which we can test for:

  • Returns a value
  • Changes a state
  • Calls a collaborator
  • Throws an exception

Which of these behaviors is expected, should be clear from the test name. Examples of test names:

  • Returns a value, should state Returns in the behavior part.
    Example Now_OnDateTime_ReturnsCurrentDateAndTime.

  • Changes a state, should state Changes in the behavior part.
    Example Close_OnFile_ChangesOpenToFalse.
    Please note, that you shouldn't test the framework, like testing a property.

  • Calls a collaborator, should state Calls in the bahavior part.
    Example Save_OnUser_CallsLogger.

  • Throws an exception, should state Throws in the behavior part.
    Example Open_NonExistingFile_ThrowsFileNotFoundException.