Lesson 11 of 93 · 4 min read · Updated

Naming Unit Tests by Intent: The Method_Scenario_ExpectedResult Pattern

A test name is the first thing you read when a build fails. A good name tells you which behaviour broke without opening the file. This lesson uses the Method_Scenario_ExpectedResult pattern that every test in this series follows, shows real examples, and explains how to tell a name that states intent from a name that only repeats the code.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3 (with xunit.runner.visualstudio and Microsoft.NET.Test.Sdk)

The Pattern: Method, Scenario, Expected Result

The name has three parts separated by underscores:

PartQuestion it answersExample
MethodWhich unit of behaviour is under test?Reserve
ScenarioIn which state or with which input?WithMoreThanStock
ExpectedResultWhat should happen?ThrowsInvalidOperation

Put together, Reserve_WithMoreThanStock_ThrowsInvalidOperation reads almost like a sentence: "Reserve, with more than the stock, throws InvalidOperationException." These are the actual test names for the Product.Reserve method and the asynchronous RemoteCatalogClient.LoadAsync method:

M02.XUnitBasics.Tests/ExceptionAssertionTests.cs

public class ExceptionAssertionTests
{
[Fact]
public void Reserve_WithMoreThanStock_ThrowsInvalidOperation()

[Fact]
public void Reserve_WithZeroQuantity_ThrowsArgumentOutOfRange()

[Fact]
public async Task LoadAsync_WhenServiceIsDown_ThrowsHttpRequestException()

[Fact]
public async Task LoadAsync_WhenCancelled_ThrowsOperationCanceled()

[Fact]
public async Task LoadAsync_WhenServiceIsUp_DoesNotThrow()
}

Method bodies are left out on purpose. Read only the names. You can already list the rules of the two methods: reserving fails on too much quantity and on zero quantity, and loading fails when the service is down or the call is cancelled, and works when the service is up. That list is a specification. The test names are documentation that the compiler keeps next to the code.

Why the Scenario Part Matters Most

The scenario is the part that people skip, and it carries the most information. Compare the name of the first test in this series, Reserve_WithAvailableStock_DecreasesStock, with the error test, Reserve_WithMoreThanStock_ThrowsInvalidOperation. Both start with Reserve. Only the scenario tells them apart. Without it, you would end up with names like Reserve_Works and Reserve_Throws, and a failure of Reserve_Throws would not tell you which of the two guard clauses broke.

Prefixes such as With, When and After make the scenario easy to spot:

  1. With... describes an input: Create_WithEmailChannel_ReturnsEmailNotification, Create_WithBlankInput_Throws.
  2. When... describes the state of the world: LoadAsync_WhenServiceIsDown_ThrowsHttpRequestException.
  3. After... describes a previous step: Price_AfterIncrease_HasExpectedValue.

Pick one style per team and keep it. Consistent names make it easy to scan a test report and group failures by method.

Name the Behaviour, Not the Implementation

The expected result should describe an outcome a caller can observe: DecreasesStock, ReturnsEmailNotification, ThrowsArgumentException. It should not describe how the code gets there. A name such as Reserve_CallsSubtractOnStockField ties the test to one implementation. If you refactor the method, the behaviour is the same but the name is now a lie.

Two more common mistakes:

  1. Numbered or vague names such as Test1, ReserveTest or ShouldWork. They force the reader to open the test body to learn anything.
  2. Names that do not match the body. When you change what a test checks, rename it. A name that says Throws on a test that now checks a return value is worse than a vague name, because it misleads.

One honest note about the examples in this series: the assertion catalogue tests, such as Equal_ComparesValues or SameNotSame_CompareReferences, are named after the xUnit API they demonstrate. That is fine for teaching material whose subject is the assertion itself. For tests of your own production code, name the behaviour of the code under test.

Names Help Beyond the Report

Consistent names pay off in daily work. A test runner groups results by class and method, so a pattern-based name sorts all Reserve_ tests together. On the command line, you can run all tests of one method with a filter:

dotnet test --filter "FullyQualifiedName~Reserve_"

Long names are fine. A test is never called from code, so nobody has to type its name. Clarity is worth more than brevity here. If a name grows past what fits on a screen, the test probably checks too many things at once, which is a design hint rather than a naming problem.

Some teams prefer sentence-style names such as Reserving_more_than_the_stock_throws, or nested classes per method. These work too. The pattern matters less than the rule behind it: the name must state the scenario and the expected behaviour.

Summary

  1. Name tests Method_Scenario_ExpectedResult, for example Reserve_WithMoreThanStock_ThrowsInvalidOperation.
  2. The scenario part separates tests of the same method. Do not skip it.
  3. Describe observable behaviour in the expected result, not implementation steps.
  4. Rename a test when its body changes. A misleading name is worse than a vague one.
  5. The list of test names for a class should read like a specification of that class.