Skip to content
Skills Library
Programming · Testing

xunit

/xunit

Expert xUnit.net testing assistance covering .NET Fact/Theory tests, constructor fixtures, and output capture. Use when writing C# unit tests, testing ASP.NET Core applications, or running `dotnet test`.

Licence
MIT
Last repository change
01.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
1
Deprecation

No signals detected. Repository changed on 01.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Expert xUnit.net testing assistance covering .NET Fact/Theory tests, constructor fixtures, and output capture. Use when writing C# unit tests, testing ASP.NET Core applications, or running `dotnet test`.

Original author description

Expert xUnit.net testing assistance covering .NET Fact/Theory tests, constructor fixtures, and output capture. Use when writing C# unit tests, testing ASP.NET Core applications, or running `dotnet test`.

How it works

  1. When to Use
  2. Quick Start
  3. Core Concepts
  4. Common Patterns
  5. Best Practices
  6. Troubleshooting
  7. References
Original SKILL.md headings · 152 lines, 597 words
SKILL.md preview
---
name: xunit
description: Expert xUnit.net testing assistance covering .NET Fact/Theory tests, constructor fixtures, and output capture. Use when writing C# unit tests, testing ASP.NET Core applications, or running `dotnet test`.
---

# xUnit.net

xUnit.net is the modern, open-source unit testing tool for .NET (C#, F#, VB). It is chosen by Microsoft/dotnet for their own repositories.

## When to Use

- **Modern .NET Core Unit Testing**: The modern, opinionated, community-preferred testing framework for C# and ASP.NET Core applications.
- **Isolated Clean Test Execution**: Enforcing a new class instance for every single test method to guarantee zero state contamination.
- **Theory-Driven Parameterized Tests**: Running tests across inline data (`[InlineData]`), member data, and class data sources.
- **Constructor-Based Test Setup**: Replacing `[SetUp]` attributes with standard C# object-oriented constructors and `IDisposable`.

## Quick Start

```csharp
using Xunit;

public class CalculatorTests
{
    [Fact]
    public void PassingTest()
    {
        Assert.Equal(4, Add(2, 2));
    }

    [Theory]
    [InlineData(3)]
    [InlineData(5)]
    [InlineData(6)]
    public void MyTheory(int value)
    {
        Assert.True(IsOdd(value));
    }
}
```

## Core Concepts

### Instance-Per-Test Lifecycle Architecture

Unlike NUnit and MSTest, xUnit instantiates a completely new instance of the test class for every `[Fact]`, preventing shared instance field state:

```text
[ Test Class ] ──new()──→ Runs Fact 1 ──Dispose()
[ Test Class ] ──new()──→ Runs Fact 2 ──Dispose()
```

### Facts vs Theories (`[Fact]` vs `[Theory]`)

- `[Fact]`: Test that is always true and tests invariant conditions.
- `[Theory]`: Parameterized test that executes across datasets:

```csharp
using Xunit;

public class OrderValidatorTests
{
    [Fact]
    public void EmptyOrder_IsInvalid()
    {
        var order = new Order();
        Assert.False(order.IsValid());
    }

    [Theory]
    [InlineData(100, "DISCOUNT10", 90)]
    [InlineData(50, "SAVE5", 45)]
    [InlineData(20, "", 20)]
    public void ApplyDiscount_CalculatesCorrectTotal(decimal price, string code, decimal expected)
    {
        var total = OrderService.CalculateTotal(price, code);
        Assert.Equal(expected, total);
    }
}
```

### Shared Context via Class Fixtures (`IClassFixture<T>`)

Shares expensive setup (database, web test servers) across tests without static state:

```csharp
public class DatabaseFixture : IDisposable
{
    public SqlConnection Connection { get; }
    public DatabaseFixture() { Connection = new SqlConnection("Server=localhost;..."); Connection.Open(); }
    public void Dispose() { Connection.Dispose(); }
}

public class CustomerRepositoryTests : IClassFixture<DatabaseFixture>
{
    private readonly DatabaseFixture _fixture;
    public CustomerRepositoryTests(DatabaseFixture fixture) => _fixture = fixture;

    [Fact]
    public void QueriesCustomerRecord() { /* Uses _fixture.Connection */ }
}
```

## Common Patterns

### Theory with InlineData and ClassData

**Problem**: Writing duplicate test methods for multiple inputs in C# applications.

**Solution**:
Use `[Theory]` with `[InlineData]`:

```csharp
using Xunit;

public class MathTests
{
    [Theory]
    [InlineData(2, 3, 5)]
    [InlineData(-1, 1, 0)]
    [InlineData(0, 0, 0)]
    public void Add_ValidInputs_ReturnsExpectedSum(int a, int b, int expected)
    {
        var calculator = new Calculator();
        var result = calculator.Add(a, b);
        Assert.Equal(expected, result);
    }
}
```

## Best Practices

**Do**:

- Use Constructors for Setup and `Dispose()` for Teardown: Implement `IDisposable` or `IAsyncLifetime` rather than looking for `[SetUp]`.
- Use `IClassFixture<T>` for Shared State: Share heavy dependencies (like Testcontainers or WebApplicationFactory) cleanly.
- Inject `ITestOutputHelper` for Logging: Write test logs via `ITestOutputHelper` rather than `Console.WriteLine()`.
- Run Tests in Parallel: Leverage xUnit's default parallelization across test collections.

**Don't**:

- Use static variables in test classes: xUnit runs test classes in parallel; static state introduces race conditions.
- Write `Assert.True(x == y)`: Use `Assert.Equal(expected, actual)` for informative failure diff messages.
- Create asynchronous void tests: Always return `async Task` from test methods; `async void` exceptions crash the test runner.

## Troubleshooting

| Error                                             | Cause                                                     | Solution                                                                  |
| :------------------------------------------------ | :-------------------------------------------------------- | :------------------------------------------------------------------------ |
| `No test matches the given testcase filter`       | Filter string doesn't match namespace or class name.      | Run `dotnet test --filter FullyQualifiedName~MathTests`.                  |
| `Console.WriteLine produces no output`            | xUnit isolates console output to prevent race conditions. | Inject `ITestOutputHelper` in constructor and call `_output.WriteLine()`. |
| `Assert.Equal() Failure: Expected ... Actual ...` | Output mismatch in assertion.                             | Review diff and check floating-point precision with tolerance arguments.  |

## References

- [xUnit Documentation](https://xunit.net/)

Versions

RepositoryScoreLicence
This page · G1Joshi/Agent-Skills100MIT
managedcode/dotnet-skills100MIT
claude-dev-suite/claude-dev-suite95MIT

Database snapshot: 13.11.2026 · package version 60975230f8cb (SHA-256 digest of the entire package)

Downloads in the last 30 days: 1 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95xunit-skill
    Generates xUnit.net tests in C#. Covers Fact/Theory, constructor injection, IClassFixture, and FluentAssertions. Use when user mentions "xUnit", "[Fact]", "[Theory]", "Assert.Equal", "C# xUnit". Triggers on: "xUnit", "[Fact]", "[Theory]", "Assert.Equal C#", "xUnit.net".
  • 100dotnet-test
    This skill should be used when running .NET tests selectively with a build-first, test-targeted workflow. Use it for running tests with xUnit focus.
  • 100dotnet-unit-tests
    .NET unit testing (C# / F# / VB.NET) with xUnit.net as the primary framework - `[Fact]` single tests, `[Theory]` + `[InlineData]`/`[ClassData]`/`[MemberData]` parametrization, class and collection fixtures (`IClassFixture` / `ICollectionFixture`), parallel-execution config,…
  • 90csharp-xunit
    xUnit testing patterns and data-driven test guidance. Use when writing or reviewing .NET unit tests.
  • 100aspnet-core-api-engineering
    Engineering skill: ASP.NET Core Web API — how to build and ship a api / service with ASP.NET Core, C#, xUnit. Use when writing, reviewing, testing or releasing code in this stack, and when turning a Celestial design or experience skill into code.
  • 100csharp-testing
    C# and .NET testing patterns with xUnit, FluentAssertions, mocking, integration tests, and test organization best practices. Use when writing or reviewing xUnit tests, mocks, or integration tests in a C# / .NET project.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.