Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .claude/docs/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,23 @@ dotnet test --treenode-filter "/*/*/ClassB/*"
- [ ] If performance-critical: profiled before/after
- [ ] If using reflection: tested AOT, added annotations
- [ ] No `.received.txt` files staged

---

## Documentation Snippets

CI compiles standalone C# declaration fences in `README.md` and `docs/docs` against packages produced by the pipeline.

Use a directive immediately before a fence when its context needs to be explicit:

```markdown
<!-- doc-test-member -->
<!-- doc-test-statements -->
<!-- doc-test-ignore: Reason this fence cannot compile independently. -->
```

Use `<!-- doc-test-ignore-file: Reason. -->` for a page whose examples share application-specific context. Ignore directives require a reason. Run the check against local packages with:

```powershell
./scripts/Verify-DocSnippets.ps1 -PackagesPath <package-directory> -Version <semver>
```
5 changes: 5 additions & 0 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ jobs:
nuget-apikey: ${{ steps.login.outputs.NUGET_API_KEY }}
publish-packages: ${{ (github.event.inputs.publish-packages || false) && matrix.os == 'ubuntu-latest' }}

- name: Compile documentation snippets
if: matrix.os == 'ubuntu-latest'
shell: pwsh
run: ./scripts/Verify-DocSnippets.ps1 -PackagesPath . -Version $env:Version

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- name: Upload Diagnostic Logs
uses: actions/upload-artifact@v7.0.1
if: always()
Expand Down
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,13 @@ await Assert.That(order.Items)

Defining your own assertion is one attribute on a plain method — TUnit generates the fluent extension for you:

<!-- doc-test-member: split-before=// Now available -->
```csharp
[GenerateAssertion]
public static bool IsPositive(this int value) => value > 0;

// Now available on Assert.That:
var account = new { Balance = 1 };
await Assert.That(account.Balance).IsPositive();
```

Expand All @@ -140,8 +142,8 @@ Inject anything into your test classes with `[ClassDataSource<T>]`. Implement `I
```csharp
public class PostgresContainer : IAsyncInitializer, IAsyncDisposable
{
public Task InitializeAsync() { /* start container */ }
public ValueTask DisposeAsync() { /* stop container */ }
public Task InitializeAsync() => Task.CompletedTask; // start container
public ValueTask DisposeAsync() => ValueTask.CompletedTask; // stop container
}

public class OrderRepositoryTests
Expand Down Expand Up @@ -220,7 +222,7 @@ public class WindowsOnlyAttribute : SkipAttribute
{
public WindowsOnlyAttribute() : base("Windows only") { }

public override Task<bool> ShouldSkip(TestContext testContext)
public override Task<bool> ShouldSkip(TestRegisteredContext testContext)
=> Task.FromResult(!OperatingSystem.IsWindows());
}

Expand Down Expand Up @@ -253,6 +255,7 @@ public class HealthCheckTests(ApiFactory factory)

Spin up your whole distributed app once per test session, with resource log forwarding and OpenTelemetry capture built in:

<!-- doc-test-ignore: Aspire sample depends on the generated Projects.MyApp_AppHost type. -->
```csharp
public class AppFixture : AspireFixture<Projects.MyApp_AppHost>;

Expand Down
8 changes: 4 additions & 4 deletions docs/docs/assertions/delegates.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ TUnit can execute your delegates for you, and this allows you to assert on the d

```csharp
[Test]
public async Task MyTest()
public async Task ThrowsNothing()
{
await Assert.That(() =>
{
Expand All @@ -19,7 +19,7 @@ TUnit can execute your delegates for you, and this allows you to assert on the d
// or

[Test]
public async Task MyTest()
public async Task ThrowsArgumentNullException()
{
await Assert.That(() =>
{
Expand All @@ -30,12 +30,12 @@ TUnit can execute your delegates for you, and this allows you to assert on the d
// or

[Test]
public async Task MyTest()
public async Task AssertThrowsAsync()
{
var argumentNullException = await Assert.ThrowsAsync<ArgumentNullException>(() =>
{
// Do something here
return Task.CompletedTask;
});
}
```
```
2 changes: 2 additions & 0 deletions docs/docs/assertions/extensibility/custom-assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
sidebar_position: 1
---

<!-- doc-test-ignore-file: Tutorial builds one custom assertion across multiple dependent snippets. -->

# Custom Assertions

The TUnit Assertions can be easily extended so that you can create your own assertions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
sidebar_position: 3
---

<!-- doc-test-ignore-file: Examples depend on custom application assertions and HTTP response models defined across separate snippets. -->

# Chaining and Converting

TUnit allows you to chain assertions that change the type being asserted, enabling fluent and expressive test code.
Expand All @@ -11,6 +13,7 @@ Chaining is especially helpful when you want to perform multiple assertions on a

For example:

<!-- doc-test-ignore: Depends on an application-provided HTTP response and custom assertions defined below. -->
```csharp
HttpResponseMessage response = ...;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
sidebar_position: 4
---

<!-- doc-test-ignore-file: Tutorial builds one custom assertion across multiple dependent snippets. -->

# Returning Data via `await`

Sometimes, you may want your assertion to return a value, such as an item found in a collection, so you can use it in further assertions or logic.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
sidebar_position: 2
---

<!-- doc-test-ignore-file: Independent examples intentionally reuse generated assertion names that collide in one compilation. -->

# Source Generator Assertions

TUnit provides source generators to simplify creating custom assertions. Instead of manually writing assertion classes and extension methods, you can decorate your methods with attributes and let the generator do the work.
Expand All @@ -21,6 +23,7 @@ The `[GenerateAssertion]` attribute allows you to turn any method into a full as

### Basic Example

<!-- doc-test-declaration: split-before=// Usage in tests: -->
```csharp
using System.ComponentModel;
using TUnit.Assertions.Attributes;
Expand Down
27 changes: 15 additions & 12 deletions docs/docs/assertions/regex-assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,26 @@ The `.Matches()` method allows you to validate strings against regular expressio
## Basic Usage

```csharp
[Test]
public async Task BasicRegexAssertions()
public partial class RegexTests
{
var email = "john.doe@example.com";
[GeneratedRegex(@"^[\w.]+@[\w.]+$")]
private static partial Regex EmailRegex();

// Assert that string matches a pattern
await Assert.That(email).Matches(@"^[\w.]+@[\w.]+$");
[Test]
public async Task BasicRegexAssertions()
{
var email = "john.doe@example.com";

// Use a compiled Regex object
var emailRegex = new Regex(@"^[\w.]+@[\w.]+$");
await Assert.That(email).Matches(emailRegex);
// Assert that string matches a pattern
await Assert.That(email).Matches(@"^[\w.]+@[\w.]+$");

// Use source-generated regex (C# 11+)
[GeneratedRegex(@"^[\w.]+@[\w.]+$")]
static partial Regex EmailRegex();
// Use a compiled Regex object
var emailRegex = new Regex(@"^[\w.]+@[\w.]+$");
await Assert.That(email).Matches(emailRegex);

await Assert.That(email).Matches(EmailRegex());
// Use source-generated regex (C# 11+)
await Assert.That(email).Matches(EmailRegex());
}
}
```

Expand Down
4 changes: 4 additions & 0 deletions docs/docs/assertions/should-syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ title: Should Syntax (Optional)
description: FluentAssertions-style value.Should().BeEqualTo() syntax via the optional TUnit.Assertions.Should NuGet package.
---

<!-- doc-test-ignore-file: Examples require the optional Should source generator and build on contextual values. -->

# Should Syntax

`TUnit.Assertions.Should` is an **optional** add-on package that exposes a FluentAssertions-style entry surface — `value.Should().BeEqualTo(...)` — on top of `TUnit.Assertions`. It's a thin layer: every Should-flavored method is generated from an existing `TUnit.Assertions` assertion, so behaviour, error messages, and async semantics are identical.
Expand Down Expand Up @@ -54,6 +56,7 @@ The `Does*` strip rule reads naturally for verbs (`DoesMatch` → `Match`, `Does

For irregulars or when the conjugation produces an unwanted name, decorate the assertion class with `[ShouldName("...")]`. The override is consulted before the conjugation rules:

<!-- doc-test-ignore: Illustrative declaration omits the abstract assertion implementation. -->
```csharp
[AssertionExtension("IsOdd")]
[ShouldName("BeAnOddNumber")]
Expand All @@ -62,6 +65,7 @@ public class OddAssertion : Assertion<int> { … }

`[AssertionExtension(NegatedMethodName = "...")]` produces a second extension method for the negated form, which the Should generator picks up and conjugates independently — `Contains` → `Contain` and `DoesNotContain` → `NotContain` come out automatically without any `[ShouldName]`. When TUnit's pattern uses **separate classes** for positive and negated forms (e.g. `EqualsAssertion` + `NotEqualsAssertion`), place a separate `[ShouldName]` on each:

<!-- doc-test-ignore: Illustrative declarations omit the abstract assertion implementations. -->
```csharp
[AssertionExtension("IsBetween")]
[ShouldName("BeWithinRange")]
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/benchmarks/methodology.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ dotnet build -c Release -p:TestFramework=MSTEST

### 2. Execution Phase
```csharp
using BenchmarkDotNet.Attributes;

[Benchmark]
public async Task TUnit()
{
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/examples/aspire.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: Samples depend on generated AppHost project types and application-specific resources. -->

# Aspire Integration Testing

TUnit provides first-class support for [Aspire](https://aspire.dev/get-started/what-is-aspire/) integration testing through the `TUnit.Aspire` package. This package eliminates the boilerplate of managing an Aspire distributed application in tests, handling the full lifecycle (build, start, wait for resources, stop, dispose) automatically.
Expand Down
3 changes: 3 additions & 0 deletions docs/docs/examples/aspnet.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: Samples depend on application Program, services, models, and infrastructure spread across the guide. -->

# ASP.NET Core Integration Testing

TUnit provides first-class support for ASP.NET Core integration testing through the `TUnit.AspNetCore` package. This package enables per-test isolation with shared infrastructure, making it easy to write fast, parallel integration tests.
Expand Down Expand Up @@ -1025,6 +1027,7 @@ public class MyTest : TestsBase

**Problem:** You set configuration values in `ConfigureWebHost` using `ConfigureAppConfiguration`, but your app's `Program.cs` doesn't see them during startup. Your breakpoint in Program.cs hits **before** the `ConfigureAppConfiguration` callback.

<!-- doc-test-ignore: Contrasts a factory override with separate application Program.cs top-level statements. -->
```csharp
// Factory - this approach has a timing issue!
protected override void ConfigureWebHost(IWebHostBuilder builder)
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/examples/complex-test-infrastructure.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: Samples depend on application-specific container and service infrastructure. -->

# Complex Test Infrastructure Orchestration

TUnit provides a property injection system that can help orchestrate complex test infrastructure setups. This page demonstrates how TUnit handles test setups that typically require manual coordination in traditional testing approaches.
Expand Down
9 changes: 9 additions & 0 deletions docs/docs/examples/fscheck.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ Property tests can return:
- **`Property`** - For advanced FsCheck properties with custom generators

```csharp
using FsCheck;
using FsCheck.Fluent;

// Boolean property
[Test, FsCheckProperty]
public bool StringConcatLength(string a, string b)
Expand Down Expand Up @@ -152,6 +155,9 @@ public bool PositiveNumbersArePositive(int value)
For simple ranges, use `Gen.Choose` directly:

```csharp
using FsCheck;
using FsCheck.Fluent;

public class PositiveIntArbitrary
{
public static Arbitrary<int> PositiveInt()
Expand All @@ -167,6 +173,9 @@ public class PositiveIntArbitrary
For custom types, compose generators using LINQ:

```csharp
using FsCheck;
using FsCheck.Fluent;

public class Person
{
public string Name { get; set; }
Expand Down
3 changes: 3 additions & 0 deletions docs/docs/examples/instrumenting-global-test-ids.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: Tutorial builds a custom identifier attribute across dependent snippets and uses an application database. -->

# Instrumenting: Global Test IDs

There are plenty use cases for having a unique identifier for each test in your test suite. If you're engineering tests that connect to a data source, you might want to ensure data isolation between the tests. One way to do that is cleaning up the data source after each test, but that prevents you from running tests cleanly in parallel, and it requires you to write either very intelligent or a lot of cleanup code. Additionally, bugs can cause data to leak between tests and make your tests flaky.
Expand Down Expand Up @@ -42,6 +44,7 @@ static class TestContextExtensions

Assign unique identifiers to all tests in the assembly by decorating in `AssemblyInfo.cs`:

<!-- doc-test-ignore: Assembly attribute depends on AssignTestIdentifiersAttribute from the preceding snippet. -->
```csharp
[assembly: AssignTestIdentifiers]
```
Expand Down
11 changes: 9 additions & 2 deletions docs/docs/examples/opentelemetry.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: Examples depend on optional exporters, application processors, and surrounding tracing setup. -->

# OpenTelemetry Tracing

TUnit emits `System.Diagnostics.Activity` trace spans at every level of the test lifecycle. When you configure an OpenTelemetry exporter (or any `ActivityListener`), you get distributed tracing for your test runs automatically. When no listener is attached, the cost is zero.
Expand Down Expand Up @@ -74,6 +76,7 @@ Then subscribe to the `"TUnit"` ActivitySource in a `[Before(TestDiscovery)]` ho
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
using OpenTelemetry.Trace;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
using OpenTelemetry.Resources;

public class TraceSetup
Expand Down Expand Up @@ -238,6 +241,7 @@ Swap the exporter in the setup code above. Each exporter needs its own NuGet pac
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
```

<!-- doc-test-ignore: Fluent fragment continues the OpenTelemetry builder configured above. -->
```csharp
.AddOtlpExporter(opts => opts.Endpoint = new Uri("http://localhost:4317"))
```
Expand All @@ -248,6 +252,7 @@ dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Exporter.Zipkin
```

<!-- doc-test-ignore: Fluent fragment continues the OpenTelemetry builder configured above. -->
```csharp
.AddZipkinExporter(opts => opts.Endpoint = new Uri("http://localhost:9411/api/v2/spans"))
```
Expand Down Expand Up @@ -334,8 +339,10 @@ public sealed class TUnitTagProcessor : BaseProcessor<Activity>
}
}

// then in your tracer builder:
.AddProcessor(new TUnitTagProcessor())
// Usage:
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddProcessor(new TUnitTagProcessor())
.Build();
```

Register the correlation processor **before** any synchronous exporter (`SimpleExportProcessor`-based). The built-in `TUnitTestCorrelationProcessor` tags at both `OnStart` and `OnEnd`, and a `SimpleExport`-wrapped exporter that runs first would serialize the activity before the tag is applied. `BatchExportProcessor` (the default for OTLP/Jaeger/Zipkin) defers serialization, so order doesn't matter there.
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/execution/engine-modes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: bUnit examples depend on Razor components and their application test context. -->

# Engine Modes

TUnit supports two execution modes, providing flexibility for different development and deployment scenarios.
Expand Down
3 changes: 3 additions & 0 deletions docs/docs/execution/parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
sidebar_position: 10
---

<!-- doc-test-ignore-file: Examples depend on application repositories, APIs, and shared limiter declarations. -->

# Controlling Parallelism

TUnit runs all tests in parallel by default. This page covers three attributes that give you fine-grained control when you need it.
Expand Down Expand Up @@ -161,6 +163,7 @@ With a limit of `2`, at most two of these 20 test invocations execute at the sam

### Assembly-Level Limiter

<!-- doc-test-ignore: Assembly attribute depends on MyParallelLimit from the preceding snippet. -->
```csharp
[assembly: ParallelLimiter<MyParallelLimit>]
```
Expand Down
5 changes: 5 additions & 0 deletions docs/docs/execution/repeating.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ public class MyTestClass
await Assert.That(result).IsEqualTo(5);
}
}

public static class Calculator
{
public static int Add(int left, int right) => left + right;
}
```

This produces 4 test runs in total: the original plus 3 repeats. In the test explorer, they appear as:
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/extending/argument-formatters.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- doc-test-ignore-file: Tutorial splits fictional SomeClass and formatter declarations across snippets. -->

# Argument Formatters

When writing data-driven tests, especially with custom classes as arguments, the test explorer may only show the class name, making it hard to distinguish test cases.
Expand Down
Loading
Loading