csharp-nunit
Original:🇺🇸 English
Translated
Get best practices for NUnit unit testing, including data-driven tests
3installs
Sourcegithub/awesome-copilot
Added on
NPX Install
npx skill4agent add github/awesome-copilot csharp-nunitTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →NUnit Best Practices
Your goal is to help me write effective unit tests with NUnit, 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, NUnit, and NUnit3TestAdapter 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
- Apply attribute to test classes
[TestFixture] - Use attribute for test methods
[Test] - Follow the Arrange-Act-Assert (AAA) pattern
- Name tests using the pattern
MethodName_Scenario_ExpectedBehavior - Use and
[SetUp]for per-test setup and teardown[TearDown] - Use and
[OneTimeSetUp]for per-class setup and teardown[OneTimeTearDown] - Use for assembly-level setup and teardown
[SetUpFixture]
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 for inline test data
[TestCase] - Use for programmatically generated test data
[TestCaseSource] - Use for simple parameter combinations
[Values] - Use for property or method-based data sources
[ValueSource] - Use for random numeric test values
[Random] - Use for sequential numeric test values
[Range] - Use or
[Combinatorial]for combining multiple parameters[Pairwise]
Assertions
- Use with constraint model (preferred NUnit style)
Assert.That - Use constraints like ,
Is.EqualTo,Is.SameAsContains.Item - Use for simple value equality (classic style)
Assert.AreEqual - Use for collection comparisons
CollectionAssert - Use for string-specific assertions
StringAssert - Use or
Assert.Throws<T>to test exceptionsAssert.ThrowsAsync<T> - Use descriptive messages in assertions for clarity on failure
Mocking and Isolation
- Consider using Moq or NSubstitute alongside NUnit
- 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 categories with
[Category("CategoryName")] - Use to control test execution order when necessary
[Order] - Use to indicate ownership
[Author("DeveloperName")] - Use to provide additional test information
[Description] - Consider for tests that shouldn't run automatically
[Explicit] - Use to temporarily skip tests
[Ignore("Reason")]