Skip to main content
rule CX Codex

testing · aaronontheweb — Claude Code rule: what it does, how to install

Defines xUnit testing conventions for .NET: project configurations, test isolation, coverage thresholds, and integration test setup.

Apache-2.0 ★ 138 updated 2025-03-29

Install into Cursor · Manually: put the files in place All methods and platforms ↓
.cursor/rules/testing.mdc
Open on GitHub

What testing does

The rule instructs AI agents to write maintainable tests for C# and .NET 8 projects. It specifies dependencies including xUnit 2.6.2, Coverlet 6.0.0, and the official test SDK. The prompt enforces Arrange-Act-Assert test layout and favors parameterized Theory tests with TheoryData instead of multiple separate Fact methods.

For lifecycle management, it guides the model to use ITestOutputHelper for logs and IClassFixture with IAsyncLifetime for shared fixtures. The rule explicitly requires Testcontainers for external infrastructure during integration tests rather than mocked services.

It also supplies CI pipeline snippets for GitHub Actions with an 80% threshold across lines, branches, and methods.

What it helps with

  • scaffold .NET 8 test project files with Coverlet and xUnit dependencies
  • convert repetitive Fact tests into parameterized Theory suites
  • manage database isolation using IAsyncLifetime and Testcontainers
  • configure GitHub Actions test execution with Cobertura coverage reports

Example prompts for the agent

  • Create an integration test for OrderProcessing using Testcontainers for SQL Server
  • Refactor these unit tests into an xUnit Theory using MemberData
  • Configure my *.Tests.csproj file with Coverlet coverage settings

How to install testing

Manually: put the files in place

.cursor/rules/testing.mdc

Frontmatter: description, globs, alwaysApply

Step by step, with commands for each platform: Cursor rules: .mdc files, four modes and what replaced .cursorrules

Questions about testing

How to install testing in Claude Code?

Save the rule content into .claude/rules/testing.md within your project repository. If you use Cursor, place it at .cursor/rules/testing.mdc.

Which files trigger this rule?

The rule targets files matching the *.cs and *.Tests.csproj patterns.

What dependencies does this rule rely on?

It configures projects for .NET 8 using xUnit 2.6.2, coverlet.collector, coverlet.msbuild, and Testcontainers for integration suites.

Source text

testing.mdc · Apache-2.0
---
description: This file provides guidelines for writing effective, maintainable tests using xUnit and related tools.
globs: *.cs,*.Tests.csproj
alwaysApply: false
---

Role Definition:
 - Test Engineer
 - Quality Assurance Specialist
 - CI/CD Expert

General:
  Description: >
    Tests should be reliable, maintainable, and provide meaningful coverage.
    Use xUnit as the primary testing framework, with proper isolation and
    clear patterns for test organization and execution.
  Requirements:
    - Use xUnit as the testing framework
    - Ensure test isolation
    - Follow consistent patterns
    - Maintain high code coverage
    - Configure proper CI/CD test execution

Project Setup:
  - Configure test projects:
      ```xml
      <Project Sdk="Microsoft.NET.Sdk">
        <PropertyGroup>
          <TargetFramework>net8.0</TargetFramework>
          <IsPackable>false</IsPackable>
          <IsTestProject>true</IsTestProject>
          <CollectCoverage>true</CollectCoverage>
          <CoverletOutputFormat>cobertura</CoverletOutputFormat>
        </PropertyGroup>
        
        <ItemGroup>
          <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
          <PackageReference Include="xunit" Version="2.6.2" />
          <PackageReference Include="xunit.runner.visualstudio" Version="2.5.4" />
          <PackageReference Include="coverlet.collector" Version="6.0.0" />
          <PackageReference Include="coverlet.msbuild" Version="6.0.0" />
        </ItemGroup>
      </Project>
      ```

Test Class Structure:
  - Use ITestOutputHelper for logging:
      ```csharp
      public class OrderProcessingTests
      {
          private readonly ITestOutputHelper _output;
          
          public OrderProcessingTests(ITestOutputHelper output)
          {
              _output = output;
          }
          
          [Fact]
          public async Task ProcessOrder_ValidOrder_Succeeds()
          {
              _output.WriteLine("Starting test with valid order");
              // Test implementation
          }
      }
      ```
  - Use fixtures for shared state:
      ```csharp
      public class DatabaseFixture : IAsyncLifetime
      {
          public DbConnection Connection { get; private set; }
          
          public async Task InitializeAsync()
          {
              Connection = new SqlConnection("connection-string");
              await Connection.OpenAsync();
          }
          
          public async Task DisposeAsync()
          {
              await Connection.DisposeAsync();
          }
      }
      
      public class OrderTests : IClassFixture<DatabaseFixture>
      {
          private readonly DatabaseFixture _fixture;
          private readonly ITestOutputHelper _output;
          
          public OrderTests(DatabaseFixture fixture, ITestOutputHelper output)
          {
              _fixture = fixture;
              _output = output;
          }
      }
      ```

Test Methods:
  - Prefer Theory over multiple Facts:
      ```csharp
      public class DiscountCalculatorTests
      {
          public static TheoryData<decimal, int, decimal> DiscountTestData => 
              new()
              {
                  { 100m, 1, 0m },      // No discount for single item
                  { 100m, 5, 5m },      // 5% for 5 items
                  { 100m, 10, 10m },    // 10% for 10 items
              };
          
          [Theory]
          [MemberData(nameof(DiscountTestData))]
          public void CalculateDiscount_ReturnsCorrectAmount(
              decimal price,
              int quantity,
              decimal expectedDiscount)
          {
              // Arrange
              var calculator = new DiscountCalculator();
              
              // Act
              var discount = calculator.Calculate(price, quantity);
              
              // Assert
              Assert.Equal(expectedDiscount, discount);
          }
      }
      ```
  - Follow Arrange-Act-Assert pattern:
      ```csharp
      [Fact]
      public async Task ProcessOrder_ValidOrder_UpdatesInventory()
      {
          // Arrange
          var order = new Order(
              OrderId.New(),
              new[] { new OrderLine("SKU123", 5) });
          var processor = new OrderProcessor(_mockRepository.Object);
          
          // Act
          var result = await processor.ProcessAsync(order);
          
          // Assert
          Assert.True(result.IsSuccess);
          _mockRepository.Verify(
              r => r.UpdateInventoryAsync(
                  It.IsAny<string>(),
                  It.IsAny<int>()),
              Times.Once);
      }
      ```

Test Isolation:
  - Use fresh data for each test:
      ```csharp
      public class OrderTests
      {
          private static Order CreateTestOrder() =>
              new(OrderId.New(), TestData.CreateOrderLines());
              
          [Fact]
          public async Task ProcessOrder_Success()
          {
              var order = CreateTestOrder();
              // Test implementation
          }
      }
      ```
  - Clean up resources:
      ```csharp
      public class IntegrationTests : IAsyncDisposable
      {
          private readonly TestServer _server;
          private readonly HttpClient _client;
          
          public IntegrationTests()
          {
              _server = new TestServer(CreateHostBuilder());
              _client = _server.CreateClient();
          }
          
          public async ValueTask DisposeAsync()
          {
              _client.Dispose();
              await _server.DisposeAsync();
          }
      }
      ```

CI/CD Configuration:
  - Configure test runs:
      ```yaml
      - name: Test
        run: |
          dotnet test --configuration Release \
                      --collect:"XPlat Code Coverage" \
                      --logger:trx \
                      --results-directory ./coverage
      
      - name: Upload coverage
        uses: actions/upload-artifact@v3
        with:
          name: coverage-results
          path: coverage/**
      ```
  - Enable code coverage:
      ```xml
      <PropertyGroup>
        <CollectCoverage>true</CollectCoverage>
        <CoverletOutputFormat>cobertura</CoverletOutputFormat>
        <CoverletOutput>./coverage/</CoverletOutput>
        <ThresholdType>line,branch,method</ThresholdType>
        <ThresholdStat>total</ThresholdStat>
        <Threshold>80</Threshold>
      </PropertyGroup>
      ```

Integration Testing:
  - Always use TestContainers for infrastructure:
      ```csharp
      // Good: Using TestContainers for database testing
      public class DatabaseTests : IAsyncLifetime
      {
          private readonly TestcontainersContainer _dbContainer;
          
          public DatabaseTests()
          {
              _dbContainer = new TestcontainersBuilder<TestcontainersContainer>()
                  .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
                  .WithEnvironment("ACCEPT_EULA", "Y")
                  .WithEnvironment("SA_PASSWORD", "Your_password123")
                  .WithPortBinding(1433, true)
                  .Build();
          }
          
          public async Task InitializeAsync()
          {
              await _dbContainer.StartAsync();
          }
          
          public async Task DisposeAsync()
          {
              await _dbContainer.DisposeAsync();
          }
      }
      
      // Good: Using TestContainers for Redis testing
      public class CacheTests : IAsyncLifetime
      {
          private readonly TestcontainersContainer _redisContainer;
          private IConnectionMultiplexer _redis;
          
          public CacheTests()
          {
              _redisContainer = new TestcontainersBuilder<TestcontainersContainer>()
                  .WithImage("redis:alpine")
                  .WithPortBinding(6379, true)
                  .Build();
          }
          
          public async Task InitializeAsync()
          {
              await _redisContainer.StartAsync();
              _redis = await ConnectionMultiplexer.ConnectAsync(
                  $"localhost:{_redisContainer.GetMappedPublicPort(6379)}");
          }
          
          public async Task DisposeAsync()
          {
              if (_redis is not null)
                  await _redis.DisposeAsync();
              await _redisContainer.DisposeAsync();
          }
      }
      
      // Good: Using TestContainers for message queue testing
      public class MessageQueueTests : IAsyncLifetime
      {
          private readonly TestcontainersContainer _rabbitContainer;
          private IConnection _connection;
          
          public MessageQueueTests()
          {
              _rabbitContainer = new TestcontainersBuilder<TestcontainersContainer>()
                  .WithImage("rabbitmq:management-alpine")
                  .WithPortBinding(5672, true)
                  .WithPortBinding(15672, true)
                  .Build();
          }
          
          public async Task InitializeAsync()
          {
              await _rabbitContainer.StartAsync();
              var factory = new ConnectionFactory
              {
                  HostName = "localhost",
                  Port = _rabbitContainer.GetMappedPublicPort(5672)
              };
              _connection = await factory.CreateConnectionAsync();
          }
          
          public async Task DisposeAsync()
          {
              await _connection.CloseAsync();
              await _rabbitContainer.DisposeAsync();
          }
      }
      ```
      
  - Avoid mocking infrastructure:
      ```csharp
      // Avoid: Mocking database
      public class DatabaseTests
      {
          private readonly Mock<IDbConnection> _mockDb = new();
          
          [Fact]
          public async Task Test_WithMockedDb()
          {
              _mockDb.Setup(db => db.QueryAsync<Order>())
                  .ReturnsAsync(new[] { new Order() });
              // Test with mocked database - can miss real database behavior
          }
      }
      
      // Good: Real database in container
      public class DatabaseTests : IAsyncLifetime
      {
          private readonly TestcontainersContainer _dbContainer;
          private IDbConnection _db;
          
          // ... TestContainers setup as shown above ...
          
          [Fact]
          public async Task Test_WithRealDb()
          {
              // Test with real database in container
              var order = await _db.QuerySingleAsync<Order>(
                  "SELECT * FROM Orders WHERE Id = @Id",
                  new { Id = 1 });
          }
      }
      ```
      
  - Use container networks for multi-container scenarios:
      ```csharp
      public class IntegrationTests : IAsyncLifetime
      {
          private readonly INetwork _network;
          private readonly TestcontainersContainer _dbContainer;
          private readonly TestcontainersContainer _redisContainer;
          
          public IntegrationTests()
          {
              _network = new TestcontainersNetwork();
              
              _dbContainer = new TestcontainersBuilder<TestcontainersContainer>()
                  .WithImage("postgres:latest")
                  .WithNetwork(_network)
                  .WithNetworkAliases("db")
                  .Build();
                  
              _redisContainer = new TestcontainersBuilder<TestcontainersContainer>()
                  .WithImage("redis:alpine")
                  .WithNetwork(_network)
                  .WithNetworkAliases("redis")
                  .Build();
          }
          
          public async Task InitializeAsync()
          {
              await _network.CreateAsync();
              await Task.WhenAll(
                  _dbContainer.StartAsync(),
                  _redisContainer.StartAsync());
          }
          
          public async Task DisposeAsync()
          {
              await Task.WhenAll(
                  _dbContainer.DisposeAsync().AsTask(),
                  _redisContainer.DisposeAsync().AsTask());
              await _network.DisposeAsync();
          }
      }
      ```

Best Practices:
  - Name tests clearly:
      ```csharp
      // Good: Clear test names
      [Fact]
      public async Task ProcessOrder_WhenInventoryAvailable_UpdatesStockAndReturnsSuccess()
      
      // Avoid: Unclear names
      [Fact]
      public async Task TestProcessOrder()
      ```
  - Use meaningful assertions:
      ```csharp
      // Good: Clear assertions
      Assert.Equal(expected, actual);
      Assert.Contains(expectedItem, collection);
      Assert.Throws<OrderException>(() => processor.Process(invalidOrder));
      
      // Avoid: Multiple assertions without context
      Assert.NotNull(result);
      Assert.True(result.Success);
      Assert.Equal(0, result.Errors.Count);
      ```
  - Handle async operations properly:
      ```csharp
      // Good: Async test method
      [Fact]
      public async Task ProcessOrder_ValidOrder_Succeeds()
      {
          await using var processor = new OrderProcessor();
          var result = await processor.ProcessAsync(order);
          Assert.True(result.IsSuccess);
      }
      
      // Avoid: Sync over async
      [Fact]
      public void ProcessOrder_ValidOrder_Succeeds()
      {
          using var processor = new OrderProcessor();
          var result = processor.ProcessAsync(order).Result;  // Can deadlock
          Assert.True(result.IsSuccess);
      }
      ```

Assertions:
  - Use xUnit's built-in assertions:
      ```csharp
      // Good: Using xUnit's built-in assertions
      public class OrderTests
      {
          [Fact]
          public void CalculateTotal_WithValidLines_ReturnsCorrectSum()
          {
              // Arrange
              var order = new Order(
                  OrderId.New(),
                  new[]
                  {
                      new OrderLine("SKU1", 2, 10.0m),
                      new OrderLine("SKU2", 1, 20.0m)
                  });
              
              // Act
              var total = order.CalculateTotal();
              
              // Assert
              Assert.Equal(40.0m, total);
          }
          
          [Fact]
          public void Order_WithInvalidLines_ThrowsException()
          {
              // Arrange
              var invalidLines = new OrderLine[] { };
              
              // Act & Assert
              var ex = Assert.Throws<ArgumentException>(() =>
                  new Order(OrderId.New(), invalidLines));
              Assert.Equal("Order must have at least one line", ex.Message);
          }
          
          [Fact]
          public void Order_WithValidData_HasExpectedProperties()
          {
              // Arrange
              var id = OrderId.New();
              var lines = new[] { new OrderLine("SKU1", 1, 10.0m) };
              
              // Act
              var order = new Order(id, lines);
              
              // Assert
              Assert.NotNull(order);
              Assert.Equal(id, order.Id);
              Assert.Single(order.Lines);
              Assert.Collection(order.Lines,
                  line =>
                  {
                      Assert.Equal("SKU1", line.Sku);
                      Assert.Equal(1, line.Quantity);
                      Assert.Equal(10.0m, line.Price);
                  });
          }
      }
      ```
      
  - Avoid third-party assertion libraries:
      ```csharp
      // Avoid: Using FluentAssertions or similar libraries
      public class OrderTests
      {
          [Fact]
          public void CalculateTotal_WithValidLines_ReturnsCorrectSum()
          {
              var order = new Order(
                  OrderId.New(),
                  new[]
                  {
                      new OrderLine("SKU1", 2, 10.0m),
                      new OrderLine("SKU2", 1, 20.0m)
                  });
              
              // Avoid: Using FluentAssertions
              order.CalculateTotal().Should().Be(40.0m);
              order.Lines.Should().HaveCount(2);
              order.Should().NotBeNull();
          }
      }
      ```
      
  - Use proper assertion types:
      ```csharp
      public class CustomerTests
      {
          [Fact]
          public void Customer_WithValidEmail_IsCreated()
          {
              // Boolean assertions
              Assert.True(customer.IsActive);
              Assert.False(customer.IsDeleted);
              
              // Equality assertions
              Assert.Equal("[email protected]", customer.Email);
              Assert.NotEqual(Guid.Empty, customer.Id);
              
              // Collection assertions
              Assert.Empty(customer.Orders);
              Assert.Contains("Admin", customer.Roles);
              Assert.DoesNotContain("Guest", customer.Roles);
              Assert.All(customer.Orders, o => Assert.NotNull(o.Id));
              
              // Type assertions
              Assert.IsType<PremiumCustomer>(customer);
              Assert.IsAssignableFrom<ICustomer>(customer);
              
              // String assertions
              Assert.StartsWith("CUST", customer.Reference);
              Assert.Contains("Premium", customer.Description);
              Assert.Matches("^CUST\\d{6}$", customer.Reference);
              
              // Range assertions
              Assert.InRange(customer.Age, 18, 100);
              
              // Reference assertions
              Assert.Same(expectedCustomer, actualCustomer);
              Assert.NotSame(differentCustomer, actualCustomer);
          }
      }
      ```
      
  - Use Assert.Collection for complex collections:
      ```csharp
      [Fact]
      public void ProcessOrder_CreatesExpectedEvents()
      {
          // Arrange
          var processor = new OrderProcessor();
          var order = CreateTestOrder();
          
          // Act
          var events = processor.Process(order);
          
          // Assert
          Assert.Collection(events,
              evt =>
              {
                  Assert.IsType<OrderReceivedEvent>(evt);
                  var received = Assert.IsType<OrderReceivedEvent>(evt);
                  Assert.Equal(order.Id, received.OrderId);
              },
              evt =>
              {
                  Assert.IsType<InventoryReservedEvent>(evt);
                  var reserved = Assert.IsType<InventoryReservedEvent>(evt);
                  Assert.Equal(order.Id, reserved.OrderId);
                  Assert.NotEmpty(reserved.ReservedItems);
              },
              evt =>
              {
                  Assert.IsType<OrderConfirmedEvent>(evt);
                  var confirmed = Assert.IsType<OrderConfirmedEvent>(evt);
                  Assert.Equal(order.Id, confirmed.OrderId);
                  Assert.True(confirmed.IsSuccess);
              });
      }
      ```

# End of Cursor Rules File 

© Aaronontheweb · Apache-2.0 · Aaronontheweb/dotnet-cursor-rules

Similar IDE rules

All IDE rules for Testing and QA →

testing by other authors comes first.

testing caliber-ai-org Defines Vitest testing patterns for Caliber, enforcing colocated test suites, environment isolation, and global LLM mocks. CX Codex +1 ★ 1,319repo stars testing jarrodwatts The testing rule sets conventions for TypeScript test files and the __tests__ directory. Use it to guide checks for success cases, failures, and edge conditions. CX Codex +1 ★ 1,064repo stars testing sangrokjung testing enforces a strict TDD workflow in Claude Code with an 80% coverage floor, Playwright E2E suites, and three test tiers. CX Codex +1 ★ 880repo stars testing justxor testing sets automated test standards for Claude Code: Arrange-Act-Assert structure, banned sleep calls, and strict boundaries for mocks. CX Codex +1 ★ 353repo stars tdd codewithmukesh tdd guides a strict red-green-refactor cycle for .NET 10 applications using xUnit v3, WebApplicationFactory, and Testcontainers. CX Codex +1 4,000installs testcontainers wshaddix A Claude Code skill with patterns for running Testcontainers in .NET integration tests. Spins up real databases and message queues in Docker instead of mocks. CX Codex +1 571installs dotnet-testing-strategy wshaddix dotnet-testing-strategy guides assistants in choosing between unit and integration tests for .NET projects. Sets directory structures and method naming patterns. CX Codex +1 624installs akka-net-testing-patterns Aaronontheweb akka-net-testing-patterns — a skill for writing unit and integration tests for Akka.NET actors with Akka.Hosting.TestKit: dependency injection, TestProbes, persistence checks. CX Codex +1 440installs migrate-xunit-to-xunit-v3 dotnet migrate-xunit-to-xunit-v3 upgrades .NET test suites from xUnit.net v2 to xunit.v3 and fixes breaking changes. Handles CPM, executable output configuration, and runner setup. CX Codex +1 4,300installs migrate-xunit-to-mstest dotnet migrate-xunit-to-mstest converts .NET test suites from xUnit.net v2 or v3 to MSTest v4 while preserving VSTest or MTP runners. Helpful when unifying test frameworks across .NET repositories. CX Codex +1 3,900installs

From the same set11

The whole set →
code-signing Enforces .NET code signing patterns and SignClient configuration for NuGet packages in CI/CD pipelines. CX Codex +1 ★ 138repo stars consuming-dotnettool The consuming-dotnettool rule keeps .NET tool dependencies in a manifest, pins their versions, and adds restore steps for CI/CD. Use it when projects need repeatable tool setup. CX Codex +1 ★ 138repo stars dependency-management Rule for secure NuGet dependency management: vulnerability scanning, license compliance, versioning via dotnet CLI. Auto-applies to project files. CX Codex +1 ★ 138repo stars solution-management solution-management standardizes .NET solution architecture with explicit SDK pinning, shared build properties, and centralized package management. CX Codex +1 ★ 138repo stars benchmarking The benchmarking rule teaches the agent to write valid .NET performance tests using BenchmarkDotNet. Useful when you need to measure code speed and track regressions. CX Codex +1 ★ 138repo stars nuget-package-publishing nuget-package-publishing — a rule that teaches the agent to pack .NET libraries into NuGet packages following industry standards: SPDX license, README, and debug symbols. CX Codex +1 ★ 138repo stars coding-style The coding-style rule guides C# structure and style, from data types to error handling. Use it when you want an agent to follow functional patterns and keep abstractions focused. CX Codex +1 ★ 138repo stars dotnet-build dotnet-build — a scoped rule for .NET repos: plain dotnet CLI commands, version bumps pulled from release notes, and separate scripts for tests and release. CX Codex +1 ★ 138repo stars

Project sponsors

Companies that keep this analytics open