Testing Conventions¶
Rule prefix: TEST · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
Home · Rule index · Naming cheat sheet
This chapter covers how unit tests are named and laid out: test classes, test methods, test doubles and builders, data sources, local variables, folders and the Arrange-Act-Assert body. Test code follows every other rule of this guide. The ones that matter most in tests are a TimeProvider or a fixed date instead of the clock (VAR-044), no secrets (SEC-020), no ConfigureAwait (ASYNC-013), and async Task instead of async void (ASYNC-011).
The examples use xUnit and the Contoso.Orders domain; FakeOrderRepository is a working in-memory IOrderRepository that keeps orders in a Dictionary<int, Order>. OrderService is the class under test and is assumed, not shown: its constructor takes an IOrderRepository, a TimeProvider and an ILogger<OrderService>, it has ShipAsync(int, CancellationToken), and it has a static FormatOrderNumber(int). The examples omit using Xunit; because a test project imports Xunit globally (<Using Include="Xunit" />). The two ShipAsync examples pass TimeProvider.System because ShipAsync fails on the unknown order before it reads the clock; a test that asserts a time uses a stub such as StubTimeProvider (TEST-012).
The naming of test projects is set by NAM-036. A project named *.Tests, or placed in a top-level tests/ folder next to the root .editorconfig, receives the test-file section [{**.Tests/**.cs,tests/**.cs}] of the shipped .editorconfig: it turns off CA1707 (underscores), sets the ReSharper method naming rule to AaBb_AaBb, AaBb, turns off the Async suffix naming rule (NAM-131) and turns off CA2007 (ASYNC-013). The section only relaxes rules. No analyzer checks any rule in this chapter, so reviewers do; rules marked Manual are listed in the "Manual review only" table in page 15.
Rule index¶
| ID | Level | Rule | Enforced |
|---|---|---|---|
| TEST-010 | DO | name each test class after the class it tests followed by Tests (OrderServiceTests for OrderService). |
Manual |
| TEST-011 | DO | name each test method <MethodUnderTest>_<Scenario>_<ExpectedResult>_Test with PascalCase segments separated by single underscores; only the <MethodUnderTest> part keeps its own Async, and nothing follows _Test (PlaceOrderAsync_EmptyCart_ThrowsArgumentException_Test). |
Manual |
| TEST-012 | DO | name a hand-written test double Fake<Name> when it is a working in-memory implementation, Stub<Name> when it returns canned answers and Spy<Name> when it records calls, and name a test-data builder <Type>Builder. |
Manual |
| TEST-013 | DO | name each [MemberData] or [ClassData] source after the scenario its rows supply (LinesWithQuantityAndPrice), never TestData, Data or Cases1. |
Manual |
| TEST-014 | DO | name the object under test after its type in camelCase (orderService), the expected value expected and the observed value actual, never sut, result1 or x. |
Manual |
| TEST-020 | DO | put each test class in <Project>.Tests at the same relative folder and namespace as the class it tests (Contoso.Orders/Shipping/CarrierClient.cs is tested in Contoso.Orders.Tests/Shipping/CarrierClientTests.cs, namespace Contoso.Orders.Tests.Shipping). |
Manual |
| TEST-021 | DO | split every test body into Arrange, Act and Assert sections, each introduced by a // Arrange, // Act or // Assert comment and separated by one blank line. |
Manual |
| TEST-022 | DO | verify one behaviour per test: write exactly one Act statement and assert only on the outcome of that statement. | Manual |
| TEST-023 | DO NOT | write loops, if or switch statements or computed expected values (string building, arithmetic over the inputs) in a test body; supply each case as a [Theory] row through [InlineData] or [MemberData] instead. |
Manual |
Test naming¶
These rules name test classes, test methods, test doubles, builders, data sources and local variables.
TEST-010¶
DO name each test class after the class it tests followed by Tests (OrderServiceTests for OrderService).
✅ Correct
namespace Contoso.Orders.Tests;
public sealed class OrderServiceTests // Class under test + Tests
{
[Fact]
public void FormatOrderNumber_OrderId42_ReturnsZeroPaddedNumber_Test()
{
// Arrange
int orderId = 42;
// Act
string actual = OrderService.FormatOrderNumber(orderId);
// Assert
Assert.Equal("ORD-000042", actual);
}
}
❌ Incorrect — a Specs suffix and a name taken from a method
namespace Contoso.Orders.Tests;
public sealed class OrderServiceSpecs // Specs suffix instead of Tests
{
}
public sealed class PlaceOrderTests // Named after a method, not after the class under test
{
}
Why: The suffix pairs OrderServiceTests with OrderService in the file list and in a search for the class name. The prefix must be the class, not a method or a scenario, because tests of several methods share one class. IDE1006 checks the casing, prefix and suffix of a kind of symbol; it cannot tell a test class from any other class, and it cannot check which word a name contains, so reviewers check this rule. The Aviva guidelines use a Specs suffix for test classes.
Scope: Test classes · Enforced: Manual · Sources: MS-TEST, AV
TEST-011¶
DO name each test method <MethodUnderTest>_<Scenario>_<ExpectedResult>_Test with PascalCase segments separated by single underscores; only the <MethodUnderTest> part keeps its own Async, and nothing follows _Test (PlaceOrderAsync_EmptyCart_ThrowsArgumentException_Test).
✅ Correct
using Microsoft.Extensions.Logging.Abstractions;
namespace Contoso.Orders.Tests;
public sealed class OrderServiceTests
{
[Fact]
public async Task ShipAsync_UnknownOrder_ThrowsOrderNotFoundException_Test() // Ends in _Test, no Async suffix
{
// Arrange
var repository = new FakeOrderRepository();
var orderService = new OrderService(repository, TimeProvider.System, NullLogger<OrderService>.Instance);
// Act
Exception? actual = await Record.ExceptionAsync(() => orderService.ShipAsync(42, CancellationToken.None));
// Assert
Assert.IsType<OrderNotFoundException>(actual);
}
}
❌ Incorrect — a sentence without the three-part pattern
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void ShippingAPendingOrderSetsItsStatus_Test() // No <Method>_<Scenario>_<Expected> pattern
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
// Act
order.Ship();
// Assert
Assert.Equal(OrderStatus.Shipped, order.Status);
}
}
❌ Incorrect — a three-part name without _Test
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Ship_PendingOrder_SetsStatusToShipped() // No _Test suffix
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
// Act
order.Ship();
// Assert
Assert.Equal(OrderStatus.Shipped, order.Status);
}
}
❌ Incorrect — an Async suffix after _Test
using Microsoft.Extensions.Logging.Abstractions;
namespace Contoso.Orders.Tests;
public sealed class OrderServiceTests
{
[Fact]
public async Task ShipAsync_UnknownOrder_ThrowsOrderNotFoundException_TestAsync() // Async suffix after _Test
{
// Arrange
var repository = new FakeOrderRepository();
var orderService = new OrderService(repository, TimeProvider.System, NullLogger<OrderService>.Instance);
// Act
Exception? actual = await Record.ExceptionAsync(() => orderService.ShipAsync(42, CancellationToken.None));
// Assert
Assert.IsType<OrderNotFoundException>(actual);
}
}
Why: A failing-test report shows only the method name. Three parts tell the reader which method broke, in which situation and what was expected, without opening the test. The _Test suffix sets each test method apart from the helper methods, builder methods and data sources in the test project, so a plain-text search for _Test( lists every test without running the tests. None of the cited sources adds a suffix to test method names, so the _Test suffix extends MS-TEST and OSH. The first part is the name of the method under test, so it keeps its own Async suffix; no later part ends in Async, because the Async suffix tells a caller to await the method and only the test runner calls a test. Nothing follows _Test, so that search finds every test; a name ending in _TestAsync would escape it. Underscores separate the parts because PascalCase segments run together in a long name. The test-file section turns off CA1707 and sets the ReSharper method rule to AaBb_AaBb, AaBb; IDE1006 needs no relaxation because its PascalCase check ignores underscores after the first segment. IDE1006 cannot select only methods marked [Fact] or [Theory], so an IDE1006 rule that required _Test would also report helper methods; reviewers check the pattern and the suffix. The Aviva guidelines use sentence-style test names with no fixed order of parts. With CA1707 on in test files, every test method name is reported.
Exceptions: A [Theory] keeps the three parts and the _Test suffix; its scenario names the situation all rows share, not one row (see TEST-013). Test classes (TEST-010), test doubles and builders (TEST-012), data sources (TEST-013), helper methods and production methods are not test methods and never end in _Test.
Scope: Methods marked [Fact] or [Theory] · Enforced: Review only (no analyzer checks the three-part pattern or the _Test suffix; the test-file section only relaxes rules, among them the underscore and Async suffix rules) · Config: resharper_csharp_naming_rule.method · Sources: MS-TEST, RT-GC, RD-NAMING, OSH, AV
TEST-012¶
DO name a hand-written test double Fake<Name> when it is a working in-memory implementation, Stub<Name> when it returns canned answers and Spy<Name> when it records calls, and name a test-data builder <Type>Builder.
✅ Correct — a stub
namespace Contoso.Orders.Tests;
internal sealed class StubTimeProvider : TimeProvider // Returns a canned answer: Stub
{
public override DateTimeOffset GetUtcNow() => new(2026, 1, 15, 9, 0, 0, TimeSpan.Zero);
}
✅ Correct — a test-data builder
namespace Contoso.Orders.Tests;
internal sealed class OrderBuilder // <Type>Builder
{
private readonly List<OrderLine> _lines = [];
private int _customerId = 7;
public OrderBuilder ForCustomer(int customerId)
{
_customerId = customerId;
return this;
}
public OrderBuilder WithLine(string sku, int quantity, decimal unitPrice)
{
_lines.Add(new OrderLine(sku, quantity, unitPrice));
return this;
}
public Order Build()
{
var order = new Order(_customerId, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
_lines.ForEach(order.AddLine);
return order;
}
}
❌ Incorrect — a double named Test
namespace Contoso.Orders.Tests;
internal sealed class TestTimeProvider : TimeProvider // Double named Test instead of Fake, Stub or Spy
{
public override DateTimeOffset GetUtcNow() => new(2026, 1, 15, 9, 0, 0, TimeSpan.Zero);
}
❌ Incorrect — a builder not named <Type>Builder
namespace Contoso.Orders.Tests;
internal sealed class OrderFactoryHelper // Builder not named <Type>Builder
{
public Order Build() => new(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
}
Why: The prefix tells the reader what the double does, so they know whether a test depends on behaviour (Fake), canned data (Stub) or recorded calls (Spy). FakeOrderRepository is a fake: it stores and returns orders like the real repository. A spy exposes what it recorded, for example a Calls list, for the Assert section. Test says nothing about the kind, and Helper or Factory hides that the type builds one <Type> step by step. A builder fixes every value a test does not care about (the customer, the creation date), so each test names only the values it asserts on. IDE1006 cannot check word choice, so reviewers apply this rule.
Scope: Hand-written test doubles and test-data builders · Enforced: Manual · Sources: MS-TEST
TEST-013¶
DO name each [MemberData] or [ClassData] source after the scenario its rows supply (LinesWithQuantityAndPrice), never TestData, Data or Cases1.
✅ Correct
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
public static TheoryData<int, decimal, decimal> LinesWithQuantityAndPrice { get; } = new() // Scenario name
{
{ 1, 9.99m, 9.99m },
{ 3, 2.50m, 7.50m }
};
[Theory]
[MemberData(nameof(LinesWithQuantityAndPrice))]
public void Total_OneLine_ReturnsQuantityTimesUnitPrice_Test(int quantity, decimal unitPrice, decimal expected)
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
order.AddLine(new OrderLine("SKU-1", quantity, unitPrice));
// Act
decimal actual = order.Total;
// Assert
Assert.Equal(expected, actual);
}
}
❌ Incorrect — a name that does not describe the scenario
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
public static TheoryData<int, decimal, decimal> TestData { get; } = new() // Name does not describe the scenario
{
{ 1, 9.99m, 9.99m },
{ 3, 2.50m, 7.50m }
};
[Theory]
[MemberData(nameof(TestData))]
public void Total_OneLine_ReturnsQuantityTimesUnitPrice_Test(int quantity, decimal unitPrice, decimal expected)
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
order.AddLine(new OrderLine("SKU-1", quantity, unitPrice));
// Act
decimal actual = order.Total;
// Assert
Assert.Equal(expected, actual);
}
}
Why: The name of the data source is the only description of the rows. A reader of [MemberData(nameof(LinesWithQuantityAndPrice))] knows which situation the rows cover without reading them. TestData is true of every data source in the project, and Cases1 forces a second look at every row. The source is a static TheoryData<...> property so that the compiler checks the types of the rows against the parameters of the test. No analyzer checks word choice, so reviewers apply this rule.
Exceptions: For simple values that an attribute can hold (int, string, bool), [InlineData] needs no named source. A decimal cannot be an attribute argument, so use [MemberData] as above.
Scope: Data sources of [Theory] tests ([MemberData], [ClassData]) · Enforced: Manual · Sources: MS-TEST
TEST-014¶
DO name the object under test after its type in camelCase (orderService), the expected value expected and the observed value actual, never sut, result1 or x.
✅ Correct
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Total_OneLine_ReturnsQuantityTimesUnitPrice_Test()
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
order.AddLine(new OrderLine("SKU-1", 2, 5m));
decimal expected = 10m;
// Act
decimal actual = order.Total;
// Assert
Assert.Equal(expected, actual);
}
}
❌ Incorrect — generic names for the object, the result and the check
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Total_OneLine_ReturnsQuantityTimesUnitPrice_Test()
{
// Arrange
var sut = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero)); // Generic object name
sut.AddLine(new OrderLine("SKU-1", 2, 5m));
decimal expected = 10m;
// Act
decimal result1 = sut.Total; // Neither expected nor actual
// Assert
Assert.Equal(expected, result1);
}
}
Why: orderService.PlaceOrderAsync(...) reads as a sentence and names the type the reader looks for in the Arrange section; sut says only that the variable is the object under test, which the Act line already shows. expected and actual follow the argument order of Assert.Equal(expected, actual), so a swapped pair is visible at a glance, and result1 hides which value is which. The MS-TEST samples name instances after their type. IDE1006 cannot check word choice, so reviewers apply this rule. sut is a common alternative name.
Scope: Local variables in test methods · Enforced: Manual · Sources: MS-TEST, OSH
Test layout¶
These rules cover where test files live and how a test body is organized.
TEST-020¶
DO put each test class in <Project>.Tests at the same relative folder and namespace as the class it tests (Contoso.Orders/Shipping/CarrierClient.cs is tested in Contoso.Orders.Tests/Shipping/CarrierClientTests.cs, namespace Contoso.Orders.Tests.Shipping).
✅ Correct
src/
Contoso.Orders/
Shipping/
CarrierClient.cs
tests/
Contoso.Orders.Tests/
Shipping/
CarrierClientTests.cs
❌ Incorrect — the test folder does not mirror the production folder
src/
Contoso.Orders/
Shipping/
CarrierClient.cs
tests/
Contoso.Orders.Tests/
Misc/
CarrierClientTests.cs // Folder does not mirror the production folder
Why: A reader finds the tests of Shipping/CarrierClient.cs by following the same path in the test project, without a search. The namespace follows the folder (NAM-032), so Contoso.Orders.Tests.Shipping holds the tests of Contoso.Orders.Shipping. The project name *.Tests, or a top-level tests/ folder, is what turns on the test-file section of the shipped .editorconfig (NAM-036); a test project outside both gets CA1707 warnings on every test name.
Scope: Test projects, test folders and test namespaces · Enforced: Manual · Sources: MS-TEST, MS-FDG-NAMESPACES
TEST-021¶
DO split every test body into Arrange, Act and Assert sections, each introduced by a // Arrange, // Act or // Assert comment and separated by one blank line.
✅ Correct
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Ship_PendingOrder_SetsStatusToShipped_Test()
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
// Act
order.Ship();
// Assert
Assert.Equal(OrderStatus.Shipped, order.Status);
}
}
❌ Incorrect — arrange, act and assert interleaved without labels
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Ship_PendingOrder_SetsStatusToShipped_Test()
{
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero)); // No Arrange label
order.Ship(); // No Act label
Assert.Equal(OrderStatus.Shipped, order.Status); // No Assert label
}
}
Why: Three labelled blocks show a reviewer which statement is the action under test and which statements check its outcome, without reading every line. The blank lines make the same split visible in a diff. To check that a call throws, capture the exception in the Act section, as in TEST-011: Exception? actual = await Record.ExceptionAsync(() => orderService.ShipAsync(42, CancellationToken.None));, then assert on actual. Do not store the Act lambda in a local: Action adding = () => order.AddLine(line); raises IDE0039 in the test project. Pass the lambda straight to Record.Exception or Record.ExceptionAsync.
Scope: Bodies of test methods · Enforced: Manual · Sources: MS-TEST
TEST-022¶
DO verify one behaviour per test: write exactly one Act statement and assert only on the outcome of that statement.
✅ Correct
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Ship_PendingOrder_MarksOrderAsShipped_Test()
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
// Act
order.Ship();
// Assert
Assert.Equal(OrderStatus.Shipped, order.Status);
Assert.True(order.IsShipped);
}
}
❌ Incorrect — two Act statements and two behaviours
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void AddLine_ThenShip_UpdatesTotalAndStatus_Test()
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
// Act
order.AddLine(new OrderLine("SKU-1", 2, 5m)); // First Act statement: the total
order.Ship(); // Second Act statement: the status
// Assert
Assert.Equal(10m, order.Total);
Assert.Equal(OrderStatus.Shipped, order.Status);
}
}
Why: A test with one Act statement has one reason to fail, and its name (<MethodUnderTest>_<Scenario>_<ExpectedResult>_Test) can describe that reason in full. Several asserts are correct when they check different facets of the same outcome, as the status and IsShipped do after Ship. Two Act statements need two tests: when the first assert fails, the second behaviour is never checked, and the test name cannot say which of the two broke.
Scope: Behaviours verified by one test method · Enforced: Manual · Sources: MS-TEST, AV
TEST-023¶
DO NOT write loops, if or switch statements or computed expected values (string building, arithmetic over the inputs) in a test body; supply each case as a [Theory] row through [InlineData] or [MemberData] instead.
✅ Correct
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
public static TheoryData<int, decimal, decimal> LinesWithQuantityAndPrice { get; } = new() // Literal totals
{
{ 1, 9.99m, 9.99m },
{ 3, 2.50m, 7.50m }
};
[Theory]
[MemberData(nameof(LinesWithQuantityAndPrice))]
public void Total_OneLine_ReturnsQuantityTimesUnitPrice_Test(int quantity, decimal unitPrice, decimal expected)
{
// Arrange
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
order.AddLine(new OrderLine("SKU-1", quantity, unitPrice));
// Act
decimal actual = order.Total;
// Assert
Assert.Equal(expected, actual);
}
}
❌ Incorrect — a loop, a conditional and a computed expected value
namespace Contoso.Orders.Tests;
public sealed class OrderTests
{
[Fact]
public void Total_SeveralQuantities_ReturnsProducts_Test()
{
// Arrange
int[] quantities = [1, 2, 3];
// Act
foreach (int quantity in quantities) // Loop in a test
{
var order = new Order(7, new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
order.AddLine(new OrderLine("SKU-1", quantity, 2m));
// Assert
if (quantity > 0) // Conditional in a test
{
Assert.Equal(quantity * 2m, order.Total); // Expected value computed from the input
}
}
}
}
Why: Logic in a test is code that needs its own tests. A loop hides which row failed, a conditional can skip the assert, and an expected value computed from the input repeats the production formula, so both can be wrong in the same way. The incorrect example compiles without a diagnostic, which is why reviewers check it. A [Theory] reports each row as its own result and keeps a literal expected value next to its inputs.
Exceptions: A test-data builder or a data source may use a loop to create rows (TEST-012); the test body may not.
Scope: Bodies of test methods · Enforced: Manual · Sources: MS-TEST
Related¶
- NAM-016: the underscore rule and its exception for test method names.
- NAM-032 and NAM-036: namespaces that match folders, and test-project names that receive the test-file section.
- NAM-131: the
Asyncsuffix and its exception for tests. - ASYNC-011 and ASYNC-013: async tests return
Taskand never callConfigureAwait. - VAR-044: fake the clock with
TimeProvider.
Sources¶
AV · MS-FDG-NAMESPACES · MS-TEST · OSH · RD-NAMING · RT-GC
Previous: Async and Concurrency · Home · Next: Secure Coding