Testing rules

Test shape, fixtures, and assertion quality.

Rules

RuleTitleCode fix
E128054Class creates temp directory without cleanup interfaceYes
E128062Test uses outdated ReferenceAssemblies — does not match project TFMYes
E128073Test method missing [Trait("Category", ...)] attributeYes
E128097Comment inside test codeYes
E128104Assertion with literal operandsNo
E128105Test method calls an out-of-repo resolver without a skip guardNo
E128107Test matches one low-value test condition (off by default)Yes
E128108Test matches two or more low-value test conditions (off by default)Yes
E128236A test waits a fixed delay instead of a signalNo
E128237A test is disabled outside the xUnit Skip formNo

Rule details

E128054: Temp directory cleanup

Flags classes that call Path.GetTempPath() in a field initializer, property initializer, or constructor without implementing IDisposable, IAsyncDisposable, or xUnit’s IAsyncLifetime. Temp directories allocated at class level leak without a cleanup interface. The code fix adds IAsyncLifetime, and adds InitializeAsync or DisposeAsync only when the class does not already declare that member.

// Before (warns)
public class TestFixture
{
    private readonly string _tempDir = Path.Combine(Path.GetTempPath(), "test");
}

// After
public class TestFixture : IDisposable
{
    private readonly string _tempDir = Path.Combine(Path.GetTempPath(), "test");
    public void Dispose() => Directory.Delete(_tempDir, recursive: true);
}

E128062: Stale ReferenceAssemblies in tests

Flags ReferenceAssemblies.Net.Net80 / Net90 usages in test code when the configured minimum framework version is higher. Tests that use older reference assemblies may miss API availability issues specific to the production target framework. Configurable via e128_minimum_framework_version in .globalconfig (default: 100 for net10.0). The known versions run from Net60 to Net110.

// Before (warns — project targets net10.0)
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,

// After
ReferenceAssemblies = ReferenceAssemblies.Net.Net100,

E128073: Missing [Trait("Category", ...)]

Flags xUnit test methods that are missing a [Trait("Category", "...")] attribute. The test runner uses category traits to filter CI, Podman, and Manual test runs; methods without a category are silently excluded from all filtered runs.

// Before (warns)
[Fact]
public async Task MyTest() { }

// After
[Fact]
[Trait("Category", "CI")]
public async Task MyTest() { }

E128097: Comment inside test code

Flags every //, /* */, and /// comment inside a class that declares an xUnit [Fact] or [Theory] method. A license header or a doc comment on the type itself stays out of scope. The test name and the assertions already state what the test checks.

// Before (warns)
[Fact]
public void ParsesValue()
{
    // Validates the happy path
    Assert.Equal(42, Parse("42"));
}

// After
[Fact]
public void ParsesValue()
{
    Assert.Equal(42, Parse("42"));
}

E128104: Assertion with literal operands

Flags an xUnit Assert call whose every argument is a literal, such as Assert.Equal("alpha", "alpha"). Such an assertion passes or fails without the code under test. Skip, SkipWhen, SkipUnless, and Fail are not checked. A named constant is not a literal, so a comparison of two constants stays allowed. No code fix.

// Before (warns)
Assert.Equal("alpha", "alpha");

// After
Assert.Equal("alpha", subject.Name);

E128105: Test method calls an out-of-repo resolver without a skip guard

Flags a [Fact] or [Theory] method that calls a resolver named in the e128_out_of_repo_resolvers option and carries no skip guard. The option holds comma-separated Type or Type.Member entries. A bare Type entry matches every member of that type. A guard is an Assert.Skip, Assert.SkipWhen, or Assert.SkipUnless call before the resolver call, or a Skip* property on the test attribute. With no option entry the rule stays silent. No code fix.

// Before (warns)
[Fact]
public void ReadsSharedFixture()
{
    var fixture = FixtureLocator.Load("shared");
    Assert.NotNull(fixture);
}

// After
[Fact]
public void ReadsSharedFixture()
{
    Assert.SkipUnless(FixtureLocator.Exists("shared"), "The shared fixture is absent.");
    var fixture = FixtureLocator.Load("shared");
    Assert.NotNull(fixture);
}

E128107: Low-value test conditions

Flags an xUnit [Fact] or [Theory] method whose shape locks an implementation detail in place. Such a test fails on every honest refactor. One condition reports E128107 at info. Two or more report E128108 at warning. Tune the severity with dotnet_diagnostic.E128107.severity or dotnet_diagnostic.E128108.severity. This repo keeps both at suggestion, so the code fix never auto-applies. The code fix deletes the whole test method.

The conditions:

  • BareSize: three statements, one assertion, and no production call
  • NameMirror: the test name repeats the called method name and almost nothing else
  • NoAssertion: the body calls production code and asserts nothing
  • SingleRowTheory: a [Theory] with one [InlineData] row
  • LiteralEcho: the assertion compares a literal with a call whose arguments are all literals
  • ExceptionMessageLock: the assertion pins an exception message string
  • MockVerifyOnly: the only assertion is a Verify call with a lambda
  • LogAssert: the only assertion is a Verify call on a logger
  • ConstructorPassthrough: the assertion reads a member back off an object built from the same literal
  • SelfFulfillingExpected: the expected value and the actual value come from the same receiver
  • MagicConstantEcho: the expected literal also appears as a returned value in the production body
  • OrderLock: Assert.Equal pins the order of a set or dictionary result
  • DuplicateCoverage: another test in the same class calls the same method with the same literal arguments

The code fix deletes the test method, so an unattended dotnet format run must not remove a test without review.

E128108: Test matches two or more low-value test conditions (off by default)

E128236: A test waits a fixed delay instead of a signal

Flags a test method that waits a fixed time: Thread.Sleep, SpinWait.SpinUntil, or a Task.Delay over a literal duration with no cancellation token. A fixed delay wastes CI time and still flakes, because the code under test does not signal completion on a fixed schedule.

A delay inside a loop stays silent, because E128211 owns the loop case. A delay with a token or a computed duration stays silent. The rule reads xUnit test methods only in the first release. The rule carries no code fix, because the signal the test should await carries application intent.

// Before (warns)
await Task.Delay(500);
Assert.Equal(3, counter.Value);

// After
await signal.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
Assert.Equal(3, counter.Value);

E128237: A test is disabled outside the xUnit Skip form

Flags a test that a mechanism other than the xUnit Skip argument disables. E128168 owns the Skip reason. This rule owns the two foreign forms: an NUnit or MSTest [Ignore] attribute, and a test method inside a literal #if false region.

An [Ignore("reason")] whose reason matches e128_tracked_ref_pattern stays silent, so a tracked skip keeps its owner and its close date. An [Ignore] with no argument reports. A test inside #if false reports at every site, because that form carries no reason. A condition the analyzer cannot decide, and an #else or #elif branch, stay silent. The rule carries no code fix, because re-enabling a test needs intent the tree does not carry.

// Before (warns)
[Test]
[Ignore("flaky on CI")]
public void WritesTheRegistryValue() { }

// After
[Fact]
public void WritesTheRegistryValue() { }