csharp-unit-testing
Comprehensive guidance for writing C# unit tests using TUnit, TUnit.Mocks, Bogus, and TUnit.Assertions.Should with project conventions
- License 许可
- GPL-3.0
- 最近更新
- 2026-06-06
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- csharp-unit-testing
- description
- Comprehensive guidance for writing C# unit tests using TUnit, TUnit.Mocks, Bogus, and TUnit.Assertions.Should with project conventions
02 资源文件 16
- 参考文档templates/assert-async-exception.md272 B
- 参考文档templates/assert-chaining.md195 B
- 参考文档templates/assert-collection.md207 B
- 参考文档templates/assert-multiple.md349 B
- 参考文档templates/assert-simple.md160 B
- 参考文档templates/assert-sync-exception.md269 B
- 参考文档templates/bogus-generate-multiple.md83 B
- 参考文档templates/bogus-test-data.md251 B
- 参考文档templates/data-error-shape.md604 B
- 参考文档templates/middleware-unit-test.md2.1 KB
- 参考文档templates/mock-argument-matching.md190 B
- 参考文档templates/mock-configure.md239 B
- 参考文档templates/mock-create.md173 B
- 参考文档templates/mock-verify.md313 B
- 参考文档templates/test-naming.md208 B
- 参考文档templates/test-structure.md869 B
03 SKILL.md 正文
csharp-unit-testing
This skill encodes best practices for writing C# unit tests in the HypermediaEngine project. It guides test implementation using a standardized stack: TUnit for the test framework, TUnit.Mocks for mocking, Bogus for test data generation, and TUnit.Assertions.Should for powerful assertions. It also reinforces project conventions like the { data, error } return shape and Assert.Multiple() failure collection.
Phase 0 — Context Load (silent)
- Read
.claude/CLAUDE.mdand.claude/rules/testing.md - Invoke
Skill("manage-memory", args: "sqa-engineer")to load persistent memory - Note the project conventions:
- All API responses use
{ data, error }shape - Test framework: TUnit
- Mocking: TUnit.Mocks
- Test data: Bogus
- Assertions: TUnit.Assertions.Should
- All API responses use
Phase 1 — C# Unit Testing Conventions
Testing Framework: TUnit
TUnit is the project's testing framework. Use it for:
- Creating test classes (mark with
[TestClass]) - Defining test methods (mark with
[Test]) - Test organization and discovery
Why TUnit: Lightweight, modern, integrates well with .NET 6+, and aligns with the HypermediaEngine architecture.
Mocking Framework: TUnit.Mocks
TUnit.Mocks handles mock creation and behavior configuration. Always use it when a unit test needs to isolate the system under test (SUT) from its dependencies.
Pattern 1: Create a mock
Pattern 2: Configure return behavior
Pattern 3: Verify invocation
Pattern 4: Argument matching
templates/mock-argument-matching.md
Why TUnit.Mocks: Zero ceremony — the mock IS the interface. Setup and verification are expressed as plain method calls, not lambda expressions.
Test Data Generation: Bogus
Bogus generates realistic test data. Always use it instead of hardcoded test data, especially for complex objects.
Pattern 1: Create a Faker instance
Pattern 2: Generate multiple instances
templates/bogus-generate-multiple.md
Why Bogus: Produces realistic, varied test data; reduces brittleness from hardcoded values; makes tests easier to read and maintain.
Assertion Library: TUnit.Assertions.Should
TUnit.Assertions.Should provides readable, fluent assertions. Always use it instead of basic Assert statements.
Pattern 1: Simple assertions
Pattern 2: Collection assertions
templates/assert-collection.md
Note: .Any(predicate) and .All(predicate) are hand-written in TUnit.Assertions.Should and take a plain Func<TItem, bool> — not nested .Should() chains.
Pattern 3: Exception assertions (Act + Assert merged)
When asserting that a method call throws an exception, assign the call to a lambda and assert on it. This merges Act and Assert into one focused block.
Async exception:
templates/assert-async-exception.md
Sync exception:
templates/assert-sync-exception.md
Critical rule: Always use TUnit.Assertions.Should's .Should().Throw<>() — this works for both Action (sync) and Func<Task> (async) delegates. Never use .ThrowAsync<>() (it does not exist in TUnit.Assertions.Should) and never use try/catch.
Note: To assert exception messages, use Assert.That() — TUnit.Assertions.Should does not expose .WithMessage() on exception assertions.
Pattern 4: And/Or chaining
Note: Do not mix .And and .Or in the same chain — TUnit will throw MixedAndOrAssertionsException.
Pattern 5: Justification
await score.Should().BeGreaterThan(70).Because("passing grade is required");
Why TUnit.Assertions.Should: Reads like English, provides rich failure messages, fluent syntax integrates seamlessly with TUnit.
Assert.Multiple: Collect All Failures
Always wrap multiple assertions in Assert.Multiple() to collect all failures before reporting. This is critical for debugging — you see all problems at once instead of fixing them one-by-one.
If any assertion fails, the block collects all failures and reports them together. This saves debugging time.
Why Assert.Multiple(): Avoids stopping at the first failure; lets you see the full picture of what went wrong in a single test run. Native to TUnit assertion framework.
The { data, error } Return Shape
All HypermediaEngine API responses use a consistent shape:
public record ApiResponse<T>(T? Data, string? Error);
Always assert BOTH Data and Error fields. Never verify only one side. This ensures the response shape is correct.
Test Naming Convention
Use descriptive test names that explain the scenario and expected outcome using the Method_Scenario_Outcome shape:
Test Structure: Arrange, Act, Assert (AAA)
Every test follows the Arrange, Act, Assert pattern to keep test logic clear and maintainable. This structure separates concerns and makes tests easier to understand at a glance.
Arrange — Set up dependencies, test data, and the system under test (SUT). Configure mocks, build test objects with Bogus, and prepare any preconditions needed.
Act — Call the method under test exactly once. This is a single line of code that invokes the SUT with the arranged inputs. Any logic here should belong in production code, not the test.
Assert — Verify that the result matches expectations using TUnit.Assertions.Should. Use Assert.Multiple() to collect all failures at once.
Critical rule: one Act per test. If a test needs to call the SUT more than once, split it into separate tests. Each test should verify a single behavior path.
Phase 2 — Complete Example: Middleware Test
Here is a complete example testing a middleware component using all conventions together:
templates/middleware-unit-test.md
Phase 3 — Key Takeaways
When writing C# unit tests for HypermediaEngine:
- Use TUnit — it's the project's test framework
- Mock with TUnit.Mocks — fluent, intuitive, and integrated with TUnit
- Generate test data with Bogus — realistic, varied, maintainable
- Assert with TUnit.Assertions.Should — readable, fluent, powerful
- Collect failures with Assert.Multiple() — see all problems at once
- Always assert both Data and Error — the
{ data, error }shape is mandatory - Name tests clearly — explain scenario and expected outcome
- Test behavior, not implementation — tests must survive refactoring
Follow these patterns consistently across all test suites.
04 同仓库更多 Skills
write-tests
Test implementation skill for HypermediaEngine. Takes a confirmed test plan from design-test-cases and produces compilable, runnable xUnit tests following project conventions. Validates coverage quality through mutation testing. Invoked by the sqa-engineer agent after the test plan is approved.
write-documentation
Structured documentation writing workflow for HypermediaEngine. Writes or updates README.md files at the repo root and in each project directory (src/, tests/, samples/, etc.) based on current implementation, ADRs, and architecture decisions.
write-adr
Writes a numbered Architecture Decision Record (ADR) for a significant architectural choice in the HypermediaEngine project. Invoked by the software-architect agent whenever a consequential design decision is made or ratified. Saves the ADR to docs/architecture/decisions/.
tunit-playwright-ui-testing
Comprehensive guidance for writing coded end-to-end UI tests in C# using TUnit.Playwright. Tests inherit from PageTest — the base class manages all browser lifecycle. Covers NuGet setup, PageTest inheritance, Page Object Model, browser configuration, parallelism limiting, and CI integration. Based on the official TUnit docs at https://tunit.dev/docs/examples/playwright.
triage
Task classification, decomposition, dependency mapping, and routing skill. Invoked by the triage-agent to break any user request into discrete, independently-routable work items with assigned priorities and agent chains.
system-design
Expert system design skill. Use PROACTIVELY to design systems, review architectures, and assist software engineers in learning design principles and implementing them in the code with design patterns.