Agent skill

Csharp Testing

by affaan-m in affaan-m/ECC

使用 xUnit、FluentAssertions、模拟、集成测试和测试组织最佳实践的 C 和 .NET 测试模式. An agent skill from affaan-m/ECC.

MITAuto-check passedTesting & QA

Install Csharp Testing

skills CLI
$ npx skills add affaan-m/ECC --skill csharp-testing -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install affaan-m/ECC csharp-testing --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/affaan-m/ECC.git skills-src && mkdir -p .claude/skills && cp -r skills-src/docs/zh-CN/skills/csharp-testing .claude/skills/csharp-testing && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
csharp-testing
GitHub stars
275k
Token cost
~2k tokens
SKILL.md length
79 words
Files
1
Skills in repo
645
Repo updated
First seen
Licence
MIT

At a glance

使用 xUnit、FluentAssertions、模拟、集成测试和测试组织最佳实践的 C 和 .NET 测试模式. An agent skill from affaan-m/ECC.

  • Tasks that involve Unit testing
  • SKILL.md covers 何时使用, 测试框架栈, 单元测试结构 and 使用 NSubstitute 进行模拟, plus 5 more sections
  • Calls dotnet

What it does

Csharp Testing is an agent skill from affaan-m/ECC. 使用 xUnit、FluentAssertions、模拟、集成测试和测试组织最佳实践的 C 和 .NET 测试模式。

Its SKILL.md is about 2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Testing & QA, covering Unit testing. It works with C# and .NET. The repository describes itself as: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. The licence is MIT.

When your agent uses it

  • Tasks that involve Unit testing

Example prompts

  • “/csharp-testing”

What it can do on your machine

Read from SKILL.md and the folder at commit ef648e0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • dotnet

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Csharp Testing loads about 2k tokens when it runs. Until then it costs about 19 tokens; SKILL.md has 79 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~19
When it runs · the whole SKILL.md, loaded when a task matches
~2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from affaan-m/ECC at commit ef648e0, republished under its MIT licence (© affaan-m). 79 words, ~1,966 tokens.

Download SKILL.mdSave it as .claude/skills/csharp-testing/SKILL.md (or your agent's skills folder).
name
csharp-testing
description
使用 xUnit、FluentAssertions、模拟、集成测试和测试组织最佳实践的 C# 和 .NET 测试模式。
origin
ECC

C# 测试模式

使用 xUnit、FluentAssertions 和现代测试实践为 .NET 应用程序提供的全面测试模式。

何时使用

  • 为 C# 代码编写新测试
  • 审查测试质量和覆盖率
  • 为 .NET 项目搭建测试基础设施
  • 调试不稳定或缓慢的测试

测试框架栈

工具用途
xUnit测试框架(.NET 首选)
FluentAssertions可读的断言语法
NSubstitute 或 Moq模拟依赖项
Testcontainers集成测试中的真实基础设施
WebApplicationFactoryASP.NET Core 集成测试
Bogus生成逼真的测试数据

单元测试结构

安排-操作-断言
csharp
public sealed class OrderServiceTests
{
    private readonly IOrderRepository _repository = Substitute.For<IOrderRepository>();
    private readonly ILogger<OrderService> _logger = Substitute.For<ILogger<OrderService>>();
    private readonly OrderService _sut;

    public OrderServiceTests()
    {
        _sut = new OrderService(_repository, _logger);
    }

    [Fact]
    public async Task PlaceOrderAsync_ReturnsSuccess_WhenRequestIsValid()
    {
        // Arrange
        var request = new CreateOrderRequest
        {
            CustomerId = "cust-123",
            Items = [new OrderItem("SKU-001", 2, 29.99m)]
        };

        // Act
        var result = await _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert
        result.IsSuccess.Should().BeTrue();
        result.Value.Should().NotBeNull();
        result.Value!.CustomerId.Should().Be("cust-123");
    }

    [Fact]
    public async Task PlaceOrderAsync_ReturnsFailure_WhenNoItems()
    {
        // Arrange
        var request = new CreateOrderRequest
        {
            CustomerId = "cust-123",
            Items = []
        };

        // Act
        var result = await _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert
        result.IsSuccess.Should().BeFalse();
        result.Error.Should().Contain("at least one item");
    }
}
使用 Theory 的参数化测试
csharp
[Theory]
[InlineData("", false)]
[InlineData("a", false)]
[InlineData("ab@c.d", false)]
[InlineData("user@example.com", true)]
[InlineData("user+tag@example.co.uk", true)]
public void IsValidEmail_ReturnsExpected(string email, bool expected)
{
    EmailValidator.IsValid(email).Should().Be(expected);
}

[Theory]
[MemberData(nameof(InvalidOrderCases))]
public async Task PlaceOrderAsync_RejectsInvalidOrders(CreateOrderRequest request, string expectedError)
{
    var result = await _sut.PlaceOrderAsync(request, CancellationToken.None);

    result.IsSuccess.Should().BeFalse();
    result.Error.Should().Contain(expectedError);
}

public static TheoryData<CreateOrderRequest, string> InvalidOrderCases => new()
{
    { new() { CustomerId = "", Items = [ValidItem()] }, "CustomerId" },
    { new() { CustomerId = "c1", Items = [] }, "at least one item" },
    { new() { CustomerId = "c1", Items = [new("", 1, 10m)] }, "SKU" },
};

使用 NSubstitute 进行模拟

csharp
[Fact]
public async Task GetOrderAsync_ReturnsNull_WhenNotFound()
{
    // Arrange
    var orderId = Guid.NewGuid();
    _repository.FindByIdAsync(orderId, Arg.Any<CancellationToken>())
        .Returns((Order?)null);

    // Act
    var result = await _sut.GetOrderAsync(orderId, CancellationToken.None);

    // Assert
    result.Should().BeNull();
}

[Fact]
public async Task PlaceOrderAsync_PersistsOrder()
{
    // Arrange
    var request = ValidOrderRequest();

    // Act
    await _sut.PlaceOrderAsync(request, CancellationToken.None);

    // Assert — verify the repository was called
    await _repository.Received(1).AddAsync(
        Arg.Is<Order>(o => o.CustomerId == request.CustomerId),
        Arg.Any<CancellationToken>());
}

ASP.NET Core 集成测试

WebApplicationFactory 设置
csharp
public sealed class OrderApiTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public OrderApiTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                // Replace real DB with in-memory for tests
                services.RemoveAll<DbContextOptions<AppDbContext>>();
                services.AddDbContext<AppDbContext>(options =>
                    options.UseInMemoryDatabase("TestDb"));
            });
        }).CreateClient();
    }

    [Fact]
    public async Task GetOrder_Returns404_WhenNotFound()
    {
        var response = await _client.GetAsync($"/api/orders/{Guid.NewGuid()}");

        response.StatusCode.Should().Be(HttpStatusCode.NotFound);
    }

    [Fact]
    public async Task CreateOrder_Returns201_WithValidRequest()
    {
        var request = new CreateOrderRequest
        {
            CustomerId = "cust-1",
            Items = [new("SKU-001", 1, 19.99m)]
        };

        var response = await _client.PostAsJsonAsync("/api/orders", request);

        response.StatusCode.Should().Be(HttpStatusCode.Created);
        response.Headers.Location.Should().NotBeNull();
    }
}
使用 Testcontainers 进行测试
csharp
public sealed class PostgresOrderRepositoryTests : IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .Build();

    private AppDbContext _db = null!;

    public async Task InitializeAsync()
    {
        await _postgres.StartAsync();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseNpgsql(_postgres.GetConnectionString())
            .Options;
        _db = new AppDbContext(options);
        await _db.Database.MigrateAsync();
    }

    public async Task DisposeAsync()
    {
        await _db.DisposeAsync();
        await _postgres.DisposeAsync();
    }

    [Fact]
    public async Task AddAsync_PersistsOrder()
    {
        var repo = new SqlOrderRepository(_db);
        var order = Order.Create("cust-1", [new OrderItem("SKU-001", 2, 10m)]);

        await repo.AddAsync(order, CancellationToken.None);

        var found = await repo.FindByIdAsync(order.Id, CancellationToken.None);
        found.Should().NotBeNull();
        found!.Items.Should().HaveCount(1);
    }
}

测试组织

tests/
  MyApp.UnitTests/
    Services/
      OrderServiceTests.cs
      PaymentServiceTests.cs
    Validators/
      EmailValidatorTests.cs
  MyApp.IntegrationTests/
    Api/
      OrderApiTests.cs
    Repositories/
      OrderRepositoryTests.cs
  MyApp.TestHelpers/
    Builders/
      OrderBuilder.cs
    Fixtures/
      DatabaseFixture.cs

测试数据构建器

csharp
public sealed class OrderBuilder
{
    private string _customerId = "cust-default";
    private readonly List<OrderItem> _items = [new("SKU-001", 1, 10m)];

    public OrderBuilder WithCustomer(string customerId)
    {
        _customerId = customerId;
        return this;
    }

    public OrderBuilder WithItem(string sku, int quantity, decimal price)
    {
        _items.Add(new OrderItem(sku, quantity, price));
        return this;
    }

    public Order Build() => Order.Create(_customerId, _items);
}

// Usage in tests
var order = new OrderBuilder()
    .WithCustomer("cust-vip")
    .WithItem("SKU-PREMIUM", 3, 99.99m)
    .Build();

常见反模式

反模式修复方法
测试实现细节测试行为和结果
共享的可变测试状态每个测试使用新实例(xUnit 通过构造函数实现)
在异步测试中使用 Thread.Sleep使用带超时的 Task.Delay 或轮询辅助方法
对 ToString() 输出进行断言对类型化属性进行断言
每个测试一个巨型断言每个测试一个逻辑断言
测试名称描述实现按行为命名:Method_ExpectedResult_WhenCondition
忽略 CancellationToken始终传递并验证取消

运行测试

bash
# Run all tests
dotnet test

# Run with coverage
dotnet test --collect:"XPlat Code Coverage"

# Run specific project
dotnet test tests/MyApp.UnitTests/

# Filter by test name
dotnet test --filter "FullyQualifiedName~OrderService"

# Watch mode during development
dotnet watch test --project tests/MyApp.UnitTests/

© affaan-m, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in docs/zh-CN/skills/csharp-testing of affaan-m/ECC.

Open the folder on GitHubat commit ef648e0

Compare with similar skills

Csharp Testing next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Csharp Testing compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Csharp Testing this skillaffaan-m/ECC275k—~2kAutomated safety check: PassMIT
ScottPlot Test RunnerScottPlot/ScottPlot6.8k—~308Automated safety check: PassMIT
Verifyvaldisiljuconoks/LocalizationProvider180—~159Automated safety check: PassApache-2.0
Csharp Tunitgithub/awesome-copilot40k1 repos~1.3kAutomated safety check: PassMIT
Csharp ConventionsGoldziher/ai-rulez158—~363Automated safety check: PassMIT
Writing Unit Tests Csharpmicrosoft-foundry/foundry-agent-webapp127—~1kAutomated safety check: PassMIT

Similar skills

  • ScottPlot Test Runner

    ScottPlot/ScottPlot

    Run or add ScottPlot 5 tests. Use for unit-test and cookbook-test work; unless explicitly asked otherwise, restrict manual test execution to the Unit Tests…

    6.8k GitHub stars~308 tokensUpdated 1 mo ago
    Testing & QAAuto-check passed
  • Verify

    valdisiljuconoks/LocalizationProvider

    Build the solution and run unit tests to verify changes are correct.

    180 GitHub stars~159 tokensUpdated 3 mo ago
    Testing & QAAuto-check passed
  • Csharp Tunit

    github/awesome-copilot

    Official

    Get best practices for TUnit unit testing, including data-driven tests

    40k GitHub starsUsed in 1 repo~1.3k tokens
    Testing & QAAuto-check passed
  • Csharp Conventions

    Goldziher/ai-rulez

    C code conventions covering .NET 8+/C 12, nullable reference types, Roslyn analyzers, xUnit, record types, async/await discipline, and dependency security.

    158 GitHub stars~363 tokensUpdated today
    Testing & QAAuto-check passed
  • Writing Unit Tests Csharp

    microsoft-foundry/foundry-agent-webapp

    Guidelines and patterns for writing unit tests in C using MSTest SDK.

    127 GitHub stars~1k tokensUpdated 5 mo ago
    Testing & QAAuto-check passed
  • Csharp Rules

    softspark/ai-toolkit

    C/.NET coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.5k tokensUpdated yesterday
    Testing & QAAuto-check passed

More from affaan-m/ECC

All 645 skills in this repo
  • Videodb

    affaan-m/ECC

    Ingest, index, search, edit, and monitor video and audio with the VideoDB Python SDK — upload from files, URLs, or RTSP feeds, build spoken and scene indexes with timestamped search and playable…

    275k GitHub starsUsed in 3 repos~3.5k tokens
    Auto-check: notes
  • Rules Distillation

    affaan-m/ECC

    Scans installed skills for principles that recur across them and proposes rule-file changes: append, revise, add a section, create a file or leave as covered.

    275k GitHub starsUsed in 2 repos~2.3k tokens
    Auto-check passed
  • Builds DRAFT counterparty agreements from one markdown template and a small JSON spec per party, with clauses picked by the party's role.

    275k GitHub stars~2.9k tokensUpdated 3 days ago
    Auto-check passed
  • Measures whether agents actually follow a skill, rule or agent definition by generating scenarios at three strictness levels and scoring tool-call traces.

    275k GitHub starsUsed in 1 repo~623 tokens
    Auto-check passed
  • Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    275k GitHub stars~3.5k tokensUpdated 3 days ago
    Auto-check passed
  • Adds one optional external Codex critique that tries to break a council's decision draft, sent to OpenAI only after you consent.

    275k GitHub stars~1.5k tokensUpdated 3 days ago
    Auto-check passed

Works with

Categories

Questions about Csharp Testing

What does Csharp Testing do?

使用 xUnit、FluentAssertions、模拟、集成测试和测试组织最佳实践的 C 和 .NET 测试模式. An agent skill from affaan-m/ECC. Csharp Testing is an agent skill from affaan-m/ECC.

When should I use Csharp Testing?

Csharp Testing fits situations like: tasks that involve Unit testing.

How do I install Csharp Testing in Claude Code?

Run `npx skills add affaan-m/ECC --skill csharp-testing -a claude-code`. Or copy the skill folder (docs/zh-CN/skills/csharp-testing in affaan-m/ECC) into .claude/skills/csharp-testing in your project. Claude Code loads it when a task matches its description.

How do I install Csharp Testing in Codex?

Run `npx skills add affaan-m/ECC --skill csharp-testing -a codex`. Or copy the skill folder (docs/zh-CN/skills/csharp-testing in affaan-m/ECC) into .agents/skills/csharp-testing in your project. Codex loads it when a task matches its description.

Can I use Csharp Testing in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add affaan-m/ECC --skill csharp-testing -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/csharp-testing, .gemini/skills/csharp-testing, .github/skills/csharp-testing and .opencode/skills/csharp-testing in your project.

What does Csharp Testing need to run?

Going by SKILL.md and its folder, Csharp Testing needs the command-line tools its instructions call (dotnet).

Does Csharp Testing access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Csharp Testing safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Csharp Testing use?

Csharp Testing is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Csharp Testing use?

About 2k tokens (SKILL.md is roughly 7.9k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Csharp Testing?

Skills that share tags, products or a category with Csharp Testing: ScottPlot Test Runner (ScottPlot/ScottPlot, 6.8k stars), Verify (valdisiljuconoks/LocalizationProvider, 180 stars), Csharp Tunit (github/awesome-copilot, 40k stars) and Csharp Conventions (Goldziher/ai-rulez, 158 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Csharp Testing?

affaan-m (a GitHub user) maintains it in affaan-m/ECC, which has 275,023 GitHub stars. The repository holds 645 skills in this directory. The repository was last updated on October 5, 2026.

Source: affaan-m/ECC on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.