csharp-xunit
Original:🇺🇸 English
Translated
Get best practices for XUnit unit testing, including data-driven tests
7.3kinstalls
Sourcegithub/awesome-copilot
Added on
NPX Install
npx skill4agent add github/awesome-copilot csharp-xunitTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →XUnit Best Practices
Your goal is to help me write effective unit tests with XUnit, covering both standard and data-driven testing approaches.
Project Setup
- Use a separate test project with naming convention
[ProjectName].Tests - Reference Microsoft.NET.Test.Sdk, xunit, and xunit.runner.visualstudio packages
- Create test classes that match the classes being tested (e.g., for
CalculatorTests)Calculator - Use .NET SDK test commands: for running tests
dotnet test
Test Structure
- No test class attributes required (unlike MSTest/NUnit)
- Use fact-based tests with attribute for simple tests
[Fact] - Follow the Arrange-Act-Assert (AAA) pattern
- Name tests using the pattern
MethodName_Scenario_ExpectedBehavior - Use constructor for setup and for teardown
IDisposable.Dispose() - Use for shared context between tests in a class
IClassFixture<T> - Use for shared context between multiple test classes
ICollectionFixture<T>
Standard Tests
- Keep tests focused on a single behavior
- Avoid testing multiple behaviors in one test method
- Use clear assertions that express intent
- Include only the assertions needed to verify the test case
- Make tests independent and idempotent (can run in any order)
- Avoid test interdependencies
Data-Driven Tests
- Use combined with data source attributes
[Theory] - Use for inline test data
[InlineData] - Use for method-based test data
[MemberData] - Use for class-based test data
[ClassData] - Create custom data attributes by implementing
DataAttribute - Use meaningful parameter names in data-driven tests
Assertions
- Use for value equality
Assert.Equal - Use for reference equality
Assert.Same - Use /
Assert.Truefor boolean conditionsAssert.False - Use /
Assert.Containsfor collectionsAssert.DoesNotContain - Use /
Assert.Matchesfor regex pattern matchingAssert.DoesNotMatch - Use or
Assert.Throws<T>to test exceptionsawait Assert.ThrowsAsync<T> - Use fluent assertions library for more readable assertions
Mocking and Isolation
- Consider using Moq or NSubstitute alongside XUnit
- Mock dependencies to isolate units under test
- Use interfaces to facilitate mocking
- Consider using a DI container for complex test setups
Test Organization
- Group tests by feature or component
- Use for categorization
[Trait("Category", "CategoryName")] - Use collection fixtures to group tests with shared dependencies
- Consider output helpers () for test diagnostics
ITestOutputHelper - Skip tests conditionally with in fact/theory attributes
Skip = "reason"