본문으로 건너뛰기
cccskills
무료GitHub에 공개

dotnet-add-testing

Adds test infrastructure to a .NET project. Scaffolds xUnit project, coverlet, layout.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md10.2 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

dotnet-add-testing

Add test infrastructure scaffolding to an existing .NET project. Creates test projects with xUnit, configures code coverage with coverlet, and sets up the conventional directory structure.

Scope

  • Test project creation with xUnit and coverlet
  • Conventional directory structure (tests/ mirroring src/)
  • Project reference wiring and test SDK configuration

Out of scope

  • In-depth testing patterns (xUnit v3, WebApplicationFactory, UI testing) -- see [skill:dotnet-testing-strategy]

Prerequisites: Run [skill:dotnet-version-detection] first to determine SDK version and TFM. Run [skill:dotnet-project-analysis] to understand existing solution structure.

Cross-references: [skill:dotnet-project-structure] for overall solution layout conventions, [skill:dotnet-scaffold-project] which includes test scaffolding in new projects, [skill:dotnet-add-analyzers] for test-specific analyzer suppressions.


Test Project Structure

Follow the convention of mirroring src/ project names under tests/:


MyApp/
├── src/
│   ├── MyApp.Core/
│   ├── MyApp.Api/
│   └── MyApp.Infrastructure/
└── tests/
    ├── MyApp.Core.UnitTests/
    ├── MyApp.Api.UnitTests/
    ├── MyApp.Api.IntegrationTests/
    └── Directory.Build.props          # Test-specific build settings

```xml

Naming conventions:

- `*.UnitTests` -- isolated tests with no external dependencies
- `*.IntegrationTests` -- tests that use real infrastructure (database, HTTP, file system)
- `*.FunctionalTests` -- end-to-end tests through the full application stack

---

## Step 1: Create the Test Project

```bash

# Create xUnit test project
dotnet new xunit -n MyApp.Core.UnitTests -o tests/MyApp.Core.UnitTests

# Add to solution
dotnet sln add tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj

# Add reference to the project under test
dotnet add tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj \
  reference src/MyApp.Core/MyApp.Core.csproj

```csharp

### Clean Up Generated Project

Remove properties already defined in `Directory.Build.props`:

```xml

<!-- tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" />
    <PackageReference Include="xunit.v3" />
    <PackageReference Include="xunit.runner.visualstudio" />
    <PackageReference Include="coverlet.collector" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\src\MyApp.Core\MyApp.Core.csproj" />
  </ItemGroup>
</Project>

```csharp

With CPM, `Version` attributes are managed in `Directory.Packages.props`. Remove them from the generated `.csproj`.

---

## Step 2: Add Test-Specific Build Properties

Create `tests/Directory.Build.props` to customize settings for all test projects:

```xml

<!-- tests/Directory.Build.props -->
<Project>
  <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
  <PropertyGroup>
    <IsPackable>false</IsPackable>
    <IsTestProject>true</IsTestProject>
    <!-- Use Microsoft.Testing.Platform v2 runner (requires Microsoft.NET.Test.Sdk 17.13+/18.x) -->
    <UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
    <!-- Relax strictness for test projects -->
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
  </PropertyGroup>
</Project>

```text

This imports the root `Directory.Build.props` (for shared settings like `Nullable`, `ImplicitUsings`, `LangVersion`) and
overrides test-specific properties.

---

## Step 3: Register Test Packages in CPM

Add test package versions to `Directory.Packages.props`:

```xml

<!-- In Directory.Packages.props -->
<ItemGroup>
  <!-- Test packages -->
  <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
  <PackageVersion Include="xunit.v3" Version="3.2.2" />
  <PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
  <PackageVersion Include="coverlet.collector" Version="8.0.0" />
</ItemGroup>

```text

### Optional: Mocking Library

Add a mocking library if the project needs test doubles:

```xml

<PackageVersion Include="NSubstitute" Version="5.3.0" />

```xml

Or for assertion libraries:

```xml

<PackageVersion Include="FluentAssertions" Version="8.0.1" />

```xml

---

## Step 4: Configure Code Coverage

### Coverlet (Collector Mode)

The `coverlet.collector` package integrates with `dotnet test` via the data collector. No additional configuration is
needed for basic coverage.

Generate coverage reports:

```bash

# Collect coverage (Cobertura format by default)
dotnet test --collect:"XPlat Code Coverage"

# Results appear in TestResults/*/coverage.cobertura.xml

```xml

### Coverage Thresholds

For CI enforcement, use `coverlet.msbuild` for threshold checks:

```xml

<!-- In test csproj or tests/Directory.Build.props -->
<PackageReference Include="coverlet.msbuild" />

```xml

```bash

# Enforce minimum coverage threshold
dotnet test /p:CollectCoverage=true \
  /p:CoverageOutputFormat=cobertura \
  /p:Threshold=80 \
  /p:ThresholdType=line

```text

### Coverage Report Generation

Use `reportgenerator` for human-readable HTML reports:

```bash

# Install globally
dotnet tool install -g dotnet-reportgenerator-globaltool

# Generate HTML report
reportgenerator \
  -reports:"tests/**/coverage.cobertura.xml" \
  -targetdir:coverage-report \
  -reporttypes:Html

```xml

---

## Step 5: Add EditorConfig Overrides for Tests

In the root `.editorconfig`, add test-specific relaxations:

```ini

[tests/**.cs]
# Allow underscores in test method names (Given_When_Then or Should_Behavior)
dotnet_diagnostic.CA1707.severity = none

# Test parameters are validated by the framework
dotnet_diagnostic.CA1062.severity = none

# ConfigureAwait not relevant in test context
dotnet_diagnostic.CA2007.severity = none

# Tests often have intentionally unused variables for assertions
dotnet_diagnostic.IDE0059.severity = suggestion

```text

---

## Step 6: Write a Starter Test

Replace the template-generated `UnitTest1.cs` with a properly structured test:

```csharp

namespace MyApp.Core.UnitTests;

public class SampleServiceTests
{
    [Fact]
    public void Method_Condition_ExpectedResult()
    {
        // Arrange
        var sut = new SampleService();

        // Act
        var result = sut.DoWork();

        // Assert
        Assert.NotNull(result);
    }

    [Theory]
    [InlineData(1, 2, 3)]
    [InlineData(0, 0, 0)]
    [InlineData(-1, 1, 0)]
    public void Add_TwoNumbers_ReturnsSum(int a, int b, int expected)
    {
        var result = Calculator.Add(a, b);
        Assert.Equal(expected, result);
    }
}

```text

### Test Naming Convention

Use the pattern `Method_Condition_ExpectedResult`:

- `CreateUser_WithValidInput_ReturnsUser`
- `GetById_WhenNotFound_ReturnsNull`
- `Delete_WithoutPermission_ThrowsUnauthorized`

---

## Verify

After adding test infrastructure, verify everything works:

```bash

# Restore (regenerate lock files if using CPM)
dotnet restore

# Build (verifies project references and analyzer config)
dotnet build --no-restore

# Run tests
dotnet test --no-build

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

```text

---

## Adding Integration Test Projects

For integration tests that need `WebApplicationFactory` or database access:

```bash

dotnet new xunit -n MyApp.Api.IntegrationTests -o tests/MyApp.Api.IntegrationTests
dotnet sln add tests/MyApp.Api.IntegrationTests/MyApp.Api.IntegrationTests.csproj
dotnet add tests/MyApp.Api.IntegrationTests/MyApp.Api.IntegrationTests.csproj \
  reference src/MyApp.Api/MyApp.Api.csproj

```csharp

Add integration test packages to CPM (match the `Microsoft.AspNetCore.Mvc.Testing` major version to the target framework
-- e.g., `8.x` for `net8.0`, `9.x` for `net9.0`, `10.x` for `net10.0`):

```xml

<!-- Version must match the project's target framework major version -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
<PackageVersion Include="Testcontainers" Version="4.3.0" />

```xml

Integration test depth (WebApplicationFactory patterns, test containers, database fixtures) -- see
[skill:dotnet-integration-testing].

---

## What's Next

This skill covers test project scaffolding. For deeper testing guidance:

- **xUnit v3 features and patterns** -- [skill:dotnet-xunit]
- **Integration testing with WebApplicationFactory** -- [skill:dotnet-integration-testing]
- **UI testing (Blazor, MAUI, Uno)** -- [skill:dotnet-blazor-testing], [skill:dotnet-maui-testing],
  [skill:dotnet-uno-testing]
- **Snapshot testing** -- [skill:dotnet-snapshot-testing]
- **Test quality and coverage enforcement** -- [skill:dotnet-test-quality]
- **CI test reporting** -- [skill:dotnet-add-ci] for starter, [skill:dotnet-gha-build-test] and
  [skill:dotnet-ado-build-test] for advanced

---



## Code Navigation (Serena MCP)

**Primary approach:** Use Serena symbol operations for efficient code navigation:

1. **Find definitions**: `serena_find_symbol` instead of text search
2. **Understand structure**: `serena_get_symbols_overview` for file organization
3. **Track references**: `serena_find_referencing_symbols` for impact analysis
4. **Precise edits**: `serena_replace_symbol_body` for clean modifications

**When to use Serena vs traditional tools:**
- ✅ **Use Serena**: Navigation, refactoring, dependency analysis, precise edits
- ✅ **Use Read/Grep**: Reading full files, pattern matching, simple text operations
- ✅ **Fallback**: If Serena unavailable, traditional tools work fine

**Example workflow:**
```text
# Instead of:
Read: src/Services/OrderService.cs
Grep: "public void ProcessOrder"

# Use:
serena_find_symbol: "OrderService/ProcessOrder"
serena_get_symbols_overview: "src/Services/OrderService.cs"
```
## References

- [xUnit Documentation](https://xunit.net/)
- [Coverlet](https://github.com/coverlet-coverage/coverlet)
- [.NET Testing Best Practices](https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices)
- [Microsoft.NET.Test.Sdk](https://www.nuget.org/packages/Microsoft.NET.Test.Sdk)
- [ReportGenerator](https://github.com/danielpalme/ReportGenerator)

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Patterns and techniques for evaluating and improving AI agent outputs.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rudironsoni/Synaxis22026년 3월 17일 업데이트

Comprehensive AI prompt engineering safety review and improvement prompt. Analyzes prompts for safety, bias, security vulnerabilities, and effectiveness while providing detailed improvement recommendations.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rudironsoni/Synaxis22026년 3월 17일 업데이트

Use when user requests research requiring multiple sources, comprehensive analysis, or synthesis across topics - technical research, domain knowledge gathering, market analysis, or learning about complex subjects

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rudironsoni/Synaxis22026년 3월 17일 업데이트

deep-wiki

무료

AI-powered wiki generation for code repositories with commands, agents, and skills

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rudironsoni/Synaxis22026년 3월 17일 업데이트

Use when building .NET 10 or C# 14 applications; when using minimal APIs, modular monolith patterns, or feature folders; when implementing HTTP resilience, Options pattern, Channels, or validation; when seeing outdated patterns like old extension method syntax

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rudironsoni/Synaxis22026년 3월 17일 업데이트

Implements accessible .NET UI. SemanticProperties, ARIA, AutomationPeer, testing per platform.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rudironsoni/Synaxis22026년 3월 17일 업데이트

rudironsoni의 스킬 모두 보기

이 스킬의 문제 신고