From 8385732838602fb25725e2503cbde12b04bbf18c Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 21 Aug 2026 14:42:44 +0100 Subject: [PATCH 1/5] test(docs): compile public snippets --- .claude/docs/workflows.md | 20 + .github/workflows/dotnet.yml | 5 + README.md | 9 +- docs/docs/assertions/delegates.md | 8 +- .../extensibility/custom-assertions.md | 2 + .../extensibility-chaining-and-converting.md | 3 + ...xtensibility-returning-items-from-await.md | 2 + .../source-generator-assertions.md | 3 + docs/docs/assertions/regex-assertions.md | 27 +- docs/docs/assertions/should-syntax.md | 4 + docs/docs/benchmarks/methodology.md | 2 + docs/docs/examples/aspire.md | 2 + docs/docs/examples/aspnet.md | 3 + .../examples/complex-test-infrastructure.md | 2 + docs/docs/examples/fscheck.md | 9 + .../examples/instrumenting-global-test-ids.md | 3 + docs/docs/examples/opentelemetry.md | 11 +- docs/docs/execution/engine-modes.md | 2 + docs/docs/execution/parallelism.md | 3 + docs/docs/execution/repeating.md | 5 + docs/docs/extending/argument-formatters.md | 2 + docs/docs/extending/data-source-generators.md | 34 +- docs/docs/extending/extension-points.md | 2 + docs/docs/extending/libraries.md | 2 + docs/docs/extending/logging.md | 2 + .../writing-your-first-test.md | 5 + docs/docs/guides/distributed-tracing.md | 3 + docs/docs/guides/performance.md | 4 +- docs/docs/migration/mstest.md | 4 +- docs/docs/migration/nunit.md | 13 +- .../testcontext-interface-organization.md | 3 + docs/docs/migration/xunit.md | 2 + docs/docs/troubleshooting.md | 5 +- docs/docs/writing-tests/aot.md | 5 +- docs/docs/writing-tests/class-data-source.md | 15 +- .../writing-tests/combined-data-source.md | 2 + .../writing-tests/data-driven-overview.md | 1 + .../writing-tests/dependency-injection.md | 2 + docs/docs/writing-tests/event-subscribing.md | 2 + docs/docs/writing-tests/explicit.md | 2 + docs/docs/writing-tests/generic-attributes.md | 5 +- docs/docs/writing-tests/matrix-tests.md | 4 - docs/docs/writing-tests/method-data-source.md | 2 + docs/docs/writing-tests/mocking/advanced.md | 2 + .../mocking/argument-matchers.md | 2 + docs/docs/writing-tests/mocking/index.md | 2 +- docs/docs/writing-tests/mocking/setup.md | 1 + .../docs/writing-tests/nested-data-sources.md | 4 +- docs/docs/writing-tests/property-injection.md | 2 + docs/docs/writing-tests/skip.md | 3 + scripts/Verify-DocSnippets.ps1 | 97 ++++ tests/TUnit.DocTests/GlobalUsings.cs | 44 ++ tests/TUnit.DocTests/Program.cs | 21 + tests/TUnit.DocTests/TUnit.DocTests.csproj | 55 ++ tools/TUnit.DocSnippetGenerator/Program.cs | 469 ++++++++++++++++++ .../TUnit.DocSnippetGenerator.csproj | 16 + 56 files changed, 905 insertions(+), 59 deletions(-) create mode 100644 scripts/Verify-DocSnippets.ps1 create mode 100644 tests/TUnit.DocTests/GlobalUsings.cs create mode 100644 tests/TUnit.DocTests/Program.cs create mode 100644 tests/TUnit.DocTests/TUnit.DocTests.csproj create mode 100644 tools/TUnit.DocSnippetGenerator/Program.cs create mode 100644 tools/TUnit.DocSnippetGenerator/TUnit.DocSnippetGenerator.csproj diff --git a/.claude/docs/workflows.md b/.claude/docs/workflows.md index 49cc55270fc..4d4165621d3 100644 --- a/.claude/docs/workflows.md +++ b/.claude/docs/workflows.md @@ -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 + + + +``` + +Use `` 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 -Version +``` diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 75cdd4ebda1..e01fd20f8b5 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -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 + - name: Upload Diagnostic Logs uses: actions/upload-artifact@v7.0.1 if: always() diff --git a/README.md b/README.md index 0aec7ea5248..069189a44d0 100644 --- a/README.md +++ b/README.md @@ -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: + ```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(); ``` @@ -140,8 +142,8 @@ Inject anything into your test classes with `[ClassDataSource]`. 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 @@ -220,7 +222,7 @@ public class WindowsOnlyAttribute : SkipAttribute { public WindowsOnlyAttribute() : base("Windows only") { } - public override Task ShouldSkip(TestContext testContext) + public override Task ShouldSkip(TestRegisteredContext testContext) => Task.FromResult(!OperatingSystem.IsWindows()); } @@ -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: + ```csharp public class AppFixture : AspireFixture; diff --git a/docs/docs/assertions/delegates.md b/docs/docs/assertions/delegates.md index 72fb18e0d37..52b2fa5cfc4 100644 --- a/docs/docs/assertions/delegates.md +++ b/docs/docs/assertions/delegates.md @@ -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(() => { @@ -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(() => { @@ -30,7 +30,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 AssertThrowsAsync() { var argumentNullException = await Assert.ThrowsAsync(() => { @@ -38,4 +38,4 @@ TUnit can execute your delegates for you, and this allows you to assert on the d return Task.CompletedTask; }); } -``` \ No newline at end of file +``` diff --git a/docs/docs/assertions/extensibility/custom-assertions.md b/docs/docs/assertions/extensibility/custom-assertions.md index 43a3e94c46c..912397912ad 100644 --- a/docs/docs/assertions/extensibility/custom-assertions.md +++ b/docs/docs/assertions/extensibility/custom-assertions.md @@ -2,6 +2,8 @@ sidebar_position: 1 --- + + # Custom Assertions The TUnit Assertions can be easily extended so that you can create your own assertions. diff --git a/docs/docs/assertions/extensibility/extensibility-chaining-and-converting.md b/docs/docs/assertions/extensibility/extensibility-chaining-and-converting.md index 175fedeee6f..e92cf8bb465 100644 --- a/docs/docs/assertions/extensibility/extensibility-chaining-and-converting.md +++ b/docs/docs/assertions/extensibility/extensibility-chaining-and-converting.md @@ -2,6 +2,8 @@ sidebar_position: 3 --- + + # Chaining and Converting TUnit allows you to chain assertions that change the type being asserted, enabling fluent and expressive test code. @@ -11,6 +13,7 @@ Chaining is especially helpful when you want to perform multiple assertions on a For example: + ```csharp HttpResponseMessage response = ...; diff --git a/docs/docs/assertions/extensibility/extensibility-returning-items-from-await.md b/docs/docs/assertions/extensibility/extensibility-returning-items-from-await.md index e975899052a..64649277267 100644 --- a/docs/docs/assertions/extensibility/extensibility-returning-items-from-await.md +++ b/docs/docs/assertions/extensibility/extensibility-returning-items-from-await.md @@ -2,6 +2,8 @@ sidebar_position: 4 --- + + # 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. diff --git a/docs/docs/assertions/extensibility/source-generator-assertions.md b/docs/docs/assertions/extensibility/source-generator-assertions.md index 6679a2b5382..99850dedbdd 100644 --- a/docs/docs/assertions/extensibility/source-generator-assertions.md +++ b/docs/docs/assertions/extensibility/source-generator-assertions.md @@ -2,6 +2,8 @@ sidebar_position: 2 --- + + # 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. @@ -21,6 +23,7 @@ The `[GenerateAssertion]` attribute allows you to turn any method into a full as ### Basic Example + ```csharp using System.ComponentModel; using TUnit.Assertions.Attributes; diff --git a/docs/docs/assertions/regex-assertions.md b/docs/docs/assertions/regex-assertions.md index 28507db9e4e..139ae3703d2 100644 --- a/docs/docs/assertions/regex-assertions.md +++ b/docs/docs/assertions/regex-assertions.md @@ -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()); + } } ``` diff --git a/docs/docs/assertions/should-syntax.md b/docs/docs/assertions/should-syntax.md index 78e54bb3957..974ced258f0 100644 --- a/docs/docs/assertions/should-syntax.md +++ b/docs/docs/assertions/should-syntax.md @@ -4,6 +4,8 @@ title: Should Syntax (Optional) description: FluentAssertions-style value.Should().BeEqualTo() syntax via the optional TUnit.Assertions.Should NuGet package. --- + + # 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. @@ -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: + ```csharp [AssertionExtension("IsOdd")] [ShouldName("BeAnOddNumber")] @@ -62,6 +65,7 @@ public class OddAssertion : Assertion { … } `[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: + ```csharp [AssertionExtension("IsBetween")] [ShouldName("BeWithinRange")] diff --git a/docs/docs/benchmarks/methodology.md b/docs/docs/benchmarks/methodology.md index 070198a8fb1..102c5fa47bf 100644 --- a/docs/docs/benchmarks/methodology.md +++ b/docs/docs/benchmarks/methodology.md @@ -156,6 +156,8 @@ dotnet build -c Release -p:TestFramework=MSTEST ### 2. Execution Phase ```csharp +using BenchmarkDotNet.Attributes; + [Benchmark] public async Task TUnit() { diff --git a/docs/docs/examples/aspire.md b/docs/docs/examples/aspire.md index 43792345cfa..3962b0d8393 100644 --- a/docs/docs/examples/aspire.md +++ b/docs/docs/examples/aspire.md @@ -1,3 +1,5 @@ + + # 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. diff --git a/docs/docs/examples/aspnet.md b/docs/docs/examples/aspnet.md index 8840e2accda..7dd8c97b653 100644 --- a/docs/docs/examples/aspnet.md +++ b/docs/docs/examples/aspnet.md @@ -1,3 +1,5 @@ + + # 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. @@ -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. + ```csharp // Factory - this approach has a timing issue! protected override void ConfigureWebHost(IWebHostBuilder builder) diff --git a/docs/docs/examples/complex-test-infrastructure.md b/docs/docs/examples/complex-test-infrastructure.md index 1b964533f63..1f1d460355c 100644 --- a/docs/docs/examples/complex-test-infrastructure.md +++ b/docs/docs/examples/complex-test-infrastructure.md @@ -1,3 +1,5 @@ + + # 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. diff --git a/docs/docs/examples/fscheck.md b/docs/docs/examples/fscheck.md index 00246fcd3ca..ba76a472251 100644 --- a/docs/docs/examples/fscheck.md +++ b/docs/docs/examples/fscheck.md @@ -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) @@ -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 PositiveInt() @@ -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; } diff --git a/docs/docs/examples/instrumenting-global-test-ids.md b/docs/docs/examples/instrumenting-global-test-ids.md index f3e9b514b7e..58662a9cdc7 100644 --- a/docs/docs/examples/instrumenting-global-test-ids.md +++ b/docs/docs/examples/instrumenting-global-test-ids.md @@ -1,3 +1,5 @@ + + # 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. @@ -42,6 +44,7 @@ static class TestContextExtensions Assign unique identifiers to all tests in the assembly by decorating in `AssemblyInfo.cs`: + ```csharp [assembly: AssignTestIdentifiers] ``` diff --git a/docs/docs/examples/opentelemetry.md b/docs/docs/examples/opentelemetry.md index 2e46d183131..377788a46e6 100644 --- a/docs/docs/examples/opentelemetry.md +++ b/docs/docs/examples/opentelemetry.md @@ -1,3 +1,5 @@ + + # 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. @@ -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; using OpenTelemetry.Resources; public class TraceSetup @@ -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 ``` + ```csharp .AddOtlpExporter(opts => opts.Endpoint = new Uri("http://localhost:4317")) ``` @@ -248,6 +252,7 @@ dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol dotnet add package OpenTelemetry.Exporter.Zipkin ``` + ```csharp .AddZipkinExporter(opts => opts.Endpoint = new Uri("http://localhost:9411/api/v2/spans")) ``` @@ -334,8 +339,10 @@ public sealed class TUnitTagProcessor : BaseProcessor } } -// 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. diff --git a/docs/docs/execution/engine-modes.md b/docs/docs/execution/engine-modes.md index 62610b435c3..1bd514da83e 100644 --- a/docs/docs/execution/engine-modes.md +++ b/docs/docs/execution/engine-modes.md @@ -1,3 +1,5 @@ + + # Engine Modes TUnit supports two execution modes, providing flexibility for different development and deployment scenarios. diff --git a/docs/docs/execution/parallelism.md b/docs/docs/execution/parallelism.md index 8ca7dc464b0..fe68d80b160 100644 --- a/docs/docs/execution/parallelism.md +++ b/docs/docs/execution/parallelism.md @@ -2,6 +2,8 @@ sidebar_position: 10 --- + + # 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. @@ -161,6 +163,7 @@ With a limit of `2`, at most two of these 20 test invocations execute at the sam ### Assembly-Level Limiter + ```csharp [assembly: ParallelLimiter] ``` diff --git a/docs/docs/execution/repeating.md b/docs/docs/execution/repeating.md index a1b536341bf..8fe9ebf0abd 100644 --- a/docs/docs/execution/repeating.md +++ b/docs/docs/execution/repeating.md @@ -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: diff --git a/docs/docs/extending/argument-formatters.md b/docs/docs/extending/argument-formatters.md index 4d2ac1bf4ed..b04eb440c83 100644 --- a/docs/docs/extending/argument-formatters.md +++ b/docs/docs/extending/argument-formatters.md @@ -1,3 +1,5 @@ + + # 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. diff --git a/docs/docs/extending/data-source-generators.md b/docs/docs/extending/data-source-generators.md index 792b8aa68e5..06cb4b1eb62 100644 --- a/docs/docs/extending/data-source-generators.md +++ b/docs/docs/extending/data-source-generators.md @@ -1,3 +1,5 @@ + + # Data Source Generators TUnit provides several base classes for creating custom data source generators: @@ -19,7 +21,7 @@ namespace MyTestProject; public class AutoFixtureGeneratorAttribute : DataSourceGeneratorAttribute { - public override IEnumerable> GenerateDataSources(DataGeneratorMetadata dataGeneratorMetadata) + protected override IEnumerable> GenerateDataSources(DataGeneratorMetadata dataGeneratorMetadata) { var fixture = new Fixture(); @@ -32,7 +34,7 @@ public class MyTestClass(SomeClass1 someClass1, SomeClass2 someClass2, SomeClass { [Test] [AutoFixtureGenerator] - public async Task Test((int value, string value2, bool value3)) + public async Task Test(int value, string value2, bool value3) { // ... } @@ -70,7 +72,7 @@ public class DatabaseDataGeneratorAttribute : AsyncDataSourceGeneratorAttribu _connectionString = connectionString; } - public override async IAsyncEnumerable> GenerateDataSources(DataGeneratorMetadata dataGeneratorMetadata) + protected override async IAsyncEnumerable>> GenerateDataSourcesAsync(DataGeneratorMetadata dataGeneratorMetadata) { await using var connection = new SqlConnection(_connectionString); await connection.OpenAsync(); @@ -79,16 +81,19 @@ public class DatabaseDataGeneratorAttribute : AsyncDataSourceGeneratorAttribu foreach (var entity in entities) { - yield return () => entity; + yield return () => Task.FromResult(entity); } } } -[Test] -[DatabaseDataGenerator("Server=localhost;Database=TestDb;")] -public async Task TestCustomerBehavior(Customer customer) +public class CustomerTests { - // Test with real customer data from database + [Test] + [DatabaseDataGenerator("Server=localhost;Database=TestDb;")] + public async Task TestCustomerBehavior(Customer customer) + { + // Test with real customer data from database + } } ``` @@ -116,7 +121,7 @@ public class AutoFixtureGeneratorAttribute : UntypedDataSourceGeneratorAttribute _types = types; } - public override IEnumerable> GenerateDataSources(DataGeneratorMetadata dataGeneratorMetadata) + protected override IEnumerable> GenerateDataSources(DataGeneratorMetadata dataGeneratorMetadata) { var fixture = new Fixture(); @@ -124,11 +129,14 @@ public class AutoFixtureGeneratorAttribute : UntypedDataSourceGeneratorAttribute } } -[Test] -[AutoFixtureGenerator(typeof(Customer), typeof(Order), typeof(Product))] -public async Task TestWithDynamicTypes(Customer customer, Order order, Product product) +public class DynamicTests { - // AutoFixture will generate test data for all three parameters + [Test] + [AutoFixtureGenerator(typeof(Customer), typeof(Order), typeof(Product))] + public async Task TestWithDynamicTypes(Customer customer, Order order, Product product) + { + // AutoFixture will generate test data for all three parameters + } } // You can also use it at the class level diff --git a/docs/docs/extending/extension-points.md b/docs/docs/extending/extension-points.md index b66f22c0433..d21d68f1385 100644 --- a/docs/docs/extending/extension-points.md +++ b/docs/docs/extending/extension-points.md @@ -1,3 +1,5 @@ + + # Extension Points TUnit provides several extension points that allow you to customize and extend the framework's behavior. These interfaces enable you to implement custom test execution logic, hook into the test lifecycle, and control parallel execution. diff --git a/docs/docs/extending/libraries.md b/docs/docs/extending/libraries.md index 13519cd53f9..3ca9d24d866 100644 --- a/docs/docs/extending/libraries.md +++ b/docs/docs/extending/libraries.md @@ -1,3 +1,5 @@ + + # Libraries When building a reusable library that defines shared hooks, custom attributes, base classes, or data sources for TUnit, reference **`TUnit.Core`** instead of the main `TUnit` package. The `TUnit` package configures a project as an executable test suite; `TUnit.Core` provides all the models and attributes needed for authoring test infrastructure without the test runner wiring. diff --git a/docs/docs/extending/logging.md b/docs/docs/extending/logging.md index 8896f853201..c71136377a8 100644 --- a/docs/docs/extending/logging.md +++ b/docs/docs/extending/logging.md @@ -1,3 +1,5 @@ + + # Logging TUnit provides a flexible logging system that captures all test output and routes it to configurable destinations called "log sinks". diff --git a/docs/docs/getting-started/writing-your-first-test.md b/docs/docs/getting-started/writing-your-first-test.md index b70e35de44f..0cc33868902 100644 --- a/docs/docs/getting-started/writing-your-first-test.md +++ b/docs/docs/getting-started/writing-your-first-test.md @@ -11,6 +11,11 @@ using TUnit.Core; namespace MyTestProject; +public class Calculator +{ + public int Add(int left, int right) => left + right; +} + public class CalculatorTests { [Test] diff --git a/docs/docs/guides/distributed-tracing.md b/docs/docs/guides/distributed-tracing.md index 346fbe1fc56..8566705305b 100644 --- a/docs/docs/guides/distributed-tracing.md +++ b/docs/docs/guides/distributed-tracing.md @@ -53,6 +53,7 @@ Install [`TUnit.OpenTelemetry`](/docs/examples/opentelemetry#option-a-zero-confi Point the OTLP exporter at Seq's ingestion endpoint: + ```csharp .AddOtlpExporter(opts => { @@ -73,6 +74,7 @@ test.case.result.status = 'fail' -- only failures ### Jaeger or Tempo + ```csharp .AddOtlpExporter(opts => opts.Endpoint = new Uri("http://localhost:4317")) ``` @@ -143,6 +145,7 @@ Use [`TestWebApplicationFactory`](/docs/examples/aspnet) or wrap with `Traced Opt out per-test when the SUT already instruments its own outbound HTTP (for example via the OpenTelemetry HttpClient instrumentation) by setting `WebApplicationTestOptions.AutoPropagateHttpClientFactory = false`: + ```csharp protected override void ConfigureTestOptions(WebApplicationTestOptions options) { diff --git a/docs/docs/guides/performance.md b/docs/docs/guides/performance.md index 5856fb2de9b..e1c7f9b8f15 100644 --- a/docs/docs/guides/performance.md +++ b/docs/docs/guides/performance.md @@ -1,3 +1,5 @@ + + # Performance Best Practices This guide provides recommendations for optimizing test performance and ensuring your TUnit test suite runs efficiently. @@ -438,4 +440,4 @@ dotnet test -- --fail-fast - **Optimize Discovery**: Keep data sources lightweight, use AOT mode, limit test combinations - **Parallelize Wisely**: Use appropriate parallel limits and grouping - **Manage Resources**: Dispose properly, avoid memory leaks, use ValueTask in hot paths -- **Batch I/O and Cache**: Group operations and cache expensive results \ No newline at end of file +- **Batch I/O and Cache**: Group operations and cache expensive results diff --git a/docs/docs/migration/mstest.md b/docs/docs/migration/mstest.md index 8f164ab913f..bf100166999 100644 --- a/docs/docs/migration/mstest.md +++ b/docs/docs/migration/mstest.md @@ -1,3 +1,5 @@ + + # Migrating from MSTest :::from-mstest Performance Boost @@ -1124,4 +1126,4 @@ public class ContextTests TUnit includes built-in code coverage support. Do **not** use Coverlet — it is incompatible with TUnit's Microsoft.Testing.Platform. -See the [Code Coverage guide](../extending/code-coverage.md) for setup and configuration. \ No newline at end of file +See the [Code Coverage guide](../extending/code-coverage.md) for setup and configuration. diff --git a/docs/docs/migration/nunit.md b/docs/docs/migration/nunit.md index adf46ea4e5d..67ab65d8426 100644 --- a/docs/docs/migration/nunit.md +++ b/docs/docs/migration/nunit.md @@ -1,3 +1,5 @@ + + # Migrating from NUnit :::from-nunit Performance Boost @@ -352,11 +354,14 @@ public async Task AdditionTest(int a, int b, int expected) ```csharp // NUnit -TestContext.WriteLine("Test output"); -TestContext.Out.WriteLine("More output"); +public void NUnitTest() +{ + NUnit.Framework.TestContext.WriteLine("Test output"); + NUnit.Framework.TestContext.Out.WriteLine("More output"); +} // TUnit (inject TestContext) -public async Task MyTest(TestContext context) +public void TUnitTest(TUnit.Core.TestContext context) { context.Output.WriteLine("Test output"); context.Output.WriteLine("More output"); @@ -840,4 +845,4 @@ public static class AssemblyHooks TUnit includes built-in code coverage support. Do **not** use Coverlet — it is incompatible with TUnit's Microsoft.Testing.Platform. -See the [Code Coverage guide](../extending/code-coverage.md) for setup and configuration. \ No newline at end of file +See the [Code Coverage guide](../extending/code-coverage.md) for setup and configuration. diff --git a/docs/docs/migration/testcontext-interface-organization.md b/docs/docs/migration/testcontext-interface-organization.md index 1a93928484e..658768dfa23 100644 --- a/docs/docs/migration/testcontext-interface-organization.md +++ b/docs/docs/migration/testcontext-interface-organization.md @@ -1,3 +1,5 @@ + + # TestContext Interface Organization Migration Guide ## Overview @@ -240,6 +242,7 @@ public void Setup() IntelliSense now groups related functionality together, making it easier to find what you need: + ```csharp TestContext.Current.Execution. // Shows only execution-related members TestContext.Current.Metadata. // Shows only metadata-related members diff --git a/docs/docs/migration/xunit.md b/docs/docs/migration/xunit.md index 33c4a8f4db9..a93d75df53b 100644 --- a/docs/docs/migration/xunit.md +++ b/docs/docs/migration/xunit.md @@ -1,3 +1,5 @@ + + # Migrating from xUnit.net :::from-xunit Performance Boost diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 87274f1b1b4..45b36ff3fc8 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -110,6 +110,7 @@ dotnet test --treenode-filter "/*/*/*/*[Category=Integration][Priority=High]" If you see trim warnings or "source generator did not generate" errors, make sure you're using AOT-compatible data sources: + ```csharp // Reflection-based — may cause AOT issues [MethodDataSource(typeof(DataClass), "GetData")] @@ -124,6 +125,7 @@ If you're using `InstanceMethodDataSource` with a `ClassDataSource` fixture that The fix is to return predefined identifiers that don't depend on initialisation: + ```csharp public class Fixture : IAsyncInitializer { @@ -142,10 +144,11 @@ public class Fixture : IAsyncInitializer Class-level and assembly-level hooks must be static: + ```csharp // Won't work — instance method [Before(Class)] -public void ClassSetup() { } +public void IncorrectClassSetup() { } // Works [Before(Class)] diff --git a/docs/docs/writing-tests/aot.md b/docs/docs/writing-tests/aot.md index eeead08f06e..8be188391b2 100644 --- a/docs/docs/writing-tests/aot.md +++ b/docs/docs/writing-tests/aot.md @@ -1,3 +1,5 @@ + + # AOT Compatibility and Generic Tests TUnit's source generation mode provides compile-time safety and performance benefits, but requires specific patterns for advanced scenarios like generic tests and complex data sources. @@ -264,6 +266,7 @@ AOT mode provides helpful compile-time diagnostics for common issues: ### Generic Test Diagnostics + ```csharp // ❌ This will generate TUnit0058 error [Test] @@ -339,4 +342,4 @@ Configure AOT behavior through your `.editorconfig` file: tunit.enable_verbose_diagnostics = false # Verbose diagnostics (default: false) ``` -These settings help balance compilation time, binary size, and functionality based on your project's needs. \ No newline at end of file +These settings help balance compilation time, binary size, and functionality based on your project's needs. diff --git a/docs/docs/writing-tests/class-data-source.md b/docs/docs/writing-tests/class-data-source.md index 769cfb1b99b..b43b68b7402 100644 --- a/docs/docs/writing-tests/class-data-source.md +++ b/docs/docs/writing-tests/class-data-source.md @@ -34,15 +34,9 @@ public class MyTestClass { // Some properties/methods/whatever! - public async Task InitializeAsync() - { - await StartServer(); - } - - public async ValueTask DisposeAsync() - { - await StopServer(); - } + public Task InitializeAsync() => Task.CompletedTask; // start server + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; // stop server } } ``` @@ -55,6 +49,7 @@ If you are using an overload that supports injecting multiple classes at once (e E.g. + ```csharp [Test] [ClassDataSource @@ -71,4 +66,4 @@ E.g. { } -``` \ No newline at end of file +``` diff --git a/docs/docs/writing-tests/combined-data-source.md b/docs/docs/writing-tests/combined-data-source.md index 0d0c018ee03..94a6b4933e5 100644 --- a/docs/docs/writing-tests/combined-data-source.md +++ b/docs/docs/writing-tests/combined-data-source.md @@ -339,6 +339,8 @@ public async Task MatrixWay( **MixedParameters:** ```csharp +public static IEnumerable GetStrings() => ["a", "b"]; + [Test] [CombinedDataSources] public async Task MixedWay( diff --git a/docs/docs/writing-tests/data-driven-overview.md b/docs/docs/writing-tests/data-driven-overview.md index 7a9a2bf09e0..3ec029621a4 100644 --- a/docs/docs/writing-tests/data-driven-overview.md +++ b/docs/docs/writing-tests/data-driven-overview.md @@ -45,6 +45,7 @@ public static IEnumerable GetCases() => ["hello", "world"]; ### Class data source (shared fixture) + ```csharp [ClassDataSource(Shared = SharedType.PerTestSession)] public class MyTests(DatabaseFixture db) diff --git a/docs/docs/writing-tests/dependency-injection.md b/docs/docs/writing-tests/dependency-injection.md index 053cbe040c9..bb7d79a774d 100644 --- a/docs/docs/writing-tests/dependency-injection.md +++ b/docs/docs/writing-tests/dependency-injection.md @@ -1,3 +1,5 @@ + + # Dependency Injection TUnit provides two mechanisms for controlling how test classes are constructed: the low-level `IClassConstructor` interface and the higher-level `DependencyInjectionDataSourceAttribute` helper. Both are registered via attributes and give full control over how constructor arguments are resolved. diff --git a/docs/docs/writing-tests/event-subscribing.md b/docs/docs/writing-tests/event-subscribing.md index 4588f926717..da714f02447 100644 --- a/docs/docs/writing-tests/event-subscribing.md +++ b/docs/docs/writing-tests/event-subscribing.md @@ -1,3 +1,5 @@ + + # Event Subscribing Objects associated with your tests have the ability to subscribe to lifecycle events generated by TUnit. diff --git a/docs/docs/writing-tests/explicit.md b/docs/docs/writing-tests/explicit.md index 2022cc70b96..e699446850c 100644 --- a/docs/docs/writing-tests/explicit.md +++ b/docs/docs/writing-tests/explicit.md @@ -1,3 +1,5 @@ + + # Explicit If you want a test to only be run explicitly (and not part of all general tests) then you can add the `[Explicit]` attribute. diff --git a/docs/docs/writing-tests/generic-attributes.md b/docs/docs/writing-tests/generic-attributes.md index 3a67be351d3..62b10edcc91 100644 --- a/docs/docs/writing-tests/generic-attributes.md +++ b/docs/docs/writing-tests/generic-attributes.md @@ -1,3 +1,5 @@ + + # Generic Attributes TUnit provides generic versions of several attributes that offer enhanced type safety and better IDE support. These attributes allow you to specify types at compile time, reducing errors and improving code maintainability. @@ -423,6 +425,7 @@ public class ReflectiveDataSource<[DynamicallyAccessedMembers( ### 1. Use Generic Attributes for Type Safety + ```csharp // ❌ Non-generic - prone to errors [MethodDataSource(typeof(DataProvider), "GetData")] @@ -490,4 +493,4 @@ Generic attributes in TUnit provide: - **AOT Compatibility**: Work well with ahead-of-time compilation - **Reusability**: Easy to create generic base attributes for common patterns -Use generic attributes whenever possible to improve code quality and maintainability in your test suites. \ No newline at end of file +Use generic attributes whenever possible to improve code quality and maintainability in your test suites. diff --git a/docs/docs/writing-tests/matrix-tests.md b/docs/docs/writing-tests/matrix-tests.md index a946e44bd4d..5b9e1e1cbfc 100644 --- a/docs/docs/writing-tests/matrix-tests.md +++ b/docs/docs/writing-tests/matrix-tests.md @@ -17,7 +17,6 @@ Here's an example: ```csharp using TUnit.Assertions; using TUnit.Assertions.Extensions; -using TUnit.Assertions.Extensions.Is; using TUnit.Core; namespace MyTestProject; @@ -56,7 +55,6 @@ You can also use the `[MatrixRange]` for numerical types. It will generated a ```csharp using TUnit.Assertions; using TUnit.Assertions.Extensions; -using TUnit.Assertions.Extensions.Is; using TUnit.Core; namespace MyTestProject; @@ -89,7 +87,6 @@ You can also specify a method that will return an `IEnumerable` of values. ```csharp using TUnit.Assertions; using TUnit.Assertions.Extensions; -using TUnit.Assertions.Extensions.Is; using TUnit.Core; namespace MyTestProject; @@ -143,7 +140,6 @@ Use exclusions to keep your test matrix manageable and avoid unnecessary or inva ```csharp using TUnit.Assertions; using TUnit.Assertions.Extensions; -using TUnit.Assertions.Extensions.Is; using TUnit.Core; namespace MyTestProject; diff --git a/docs/docs/writing-tests/method-data-source.md b/docs/docs/writing-tests/method-data-source.md index 7b52ecf058d..8b277dafa0b 100644 --- a/docs/docs/writing-tests/method-data-source.md +++ b/docs/docs/writing-tests/method-data-source.md @@ -26,6 +26,8 @@ If you return a reference to the same object, tests may interfere with each othe Here's the simplest example — a method that returns a single `Func`, creating one test case: ```csharp +public record AdditionTestData(int Value1, int Value2, int ExpectedResult); + public static class MyTestDataSources { public static Func SingleTestCase() diff --git a/docs/docs/writing-tests/mocking/advanced.md b/docs/docs/writing-tests/mocking/advanced.md index 4a044b99ae3..83220d8e302 100644 --- a/docs/docs/writing-tests/mocking/advanced.md +++ b/docs/docs/writing-tests/mocking/advanced.md @@ -2,6 +2,8 @@ sidebar_position: 5 --- + + # Advanced Features ## Events diff --git a/docs/docs/writing-tests/mocking/argument-matchers.md b/docs/docs/writing-tests/mocking/argument-matchers.md index 1bdc8929718..200fc192a72 100644 --- a/docs/docs/writing-tests/mocking/argument-matchers.md +++ b/docs/docs/writing-tests/mocking/argument-matchers.md @@ -2,6 +2,8 @@ sidebar_position: 4 --- + + # Argument Matchers Argument matchers control which calls a setup or verification matches. The same matchers work in both contexts — the chain method determines whether it's a setup or verification. diff --git a/docs/docs/writing-tests/mocking/index.md b/docs/docs/writing-tests/mocking/index.md index 9b1becc6a39..e302a95fe93 100644 --- a/docs/docs/writing-tests/mocking/index.md +++ b/docs/docs/writing-tests/mocking/index.md @@ -127,7 +127,7 @@ var mock = IService.Mock(); mock.GetUser(Any()).Returns(user); // setup — .Returns() makes it a stub mock.GetUser(42).WasCalled(Times.Once); // verify — .WasCalled() makes it a check mock.RaiseOnMessage("hi"); // raise events — Raise{EventName}() -mock.Object // the T instance (also available via direct cast) +_ = mock.Object; // the T instance (also available via direct cast) ``` ### Typed Mock Wrapper diff --git a/docs/docs/writing-tests/mocking/setup.md b/docs/docs/writing-tests/mocking/setup.md index ec5cfd3ebbc..353df93f258 100644 --- a/docs/docs/writing-tests/mocking/setup.md +++ b/docs/docs/writing-tests/mocking/setup.md @@ -199,6 +199,7 @@ Interfaces that have static abstract members (directly or inherited) cannot be u Use `[assembly: GenerateMock(typeof(T))]` to work around this. The source generator produces a bridge interface (suffixed `_Mockable`) that provides default implementations for the static abstract members: + ```csharp using TUnit.Mocks; diff --git a/docs/docs/writing-tests/nested-data-sources.md b/docs/docs/writing-tests/nested-data-sources.md index 802cbbae60a..a2fa4a5536f 100644 --- a/docs/docs/writing-tests/nested-data-sources.md +++ b/docs/docs/writing-tests/nested-data-sources.md @@ -2,6 +2,8 @@ sidebar_position: 7 --- + + # Nested Data Sources with Initialization When writing integration tests, you often need complex test fixtures that depend on other initialized resources. TUnit's nested data source initialization feature makes this elegant and automatic. @@ -270,4 +272,4 @@ Nested data source initialization in TUnit: - ✅ Works seamlessly with async operations - ✅ Provides automatic cleanup -This makes integration testing with complex dependencies simple and maintainable. \ No newline at end of file +This makes integration testing with complex dependencies simple and maintainable. diff --git a/docs/docs/writing-tests/property-injection.md b/docs/docs/writing-tests/property-injection.md index d9c0d9dd165..aa0a7ec1a78 100644 --- a/docs/docs/writing-tests/property-injection.md +++ b/docs/docs/writing-tests/property-injection.md @@ -1,3 +1,5 @@ + + # Property Injection TUnit's AOT-compatible property injection system makes it easy to initialize properties on your test class with compile-time safety and excellent performance. diff --git a/docs/docs/writing-tests/skip.md b/docs/docs/writing-tests/skip.md index 02d8387d03d..985e63ffd13 100644 --- a/docs/docs/writing-tests/skip.md +++ b/docs/docs/writing-tests/skip.md @@ -1,3 +1,5 @@ + + # Skipping Tests If you want to simply skip a test, just place a `[Skip(reason)]` attribute on your test with an explanation of why you're skipping it. @@ -33,6 +35,7 @@ public class WindowsOnlyAttribute() : SkipAttribute("This test is only supported } ``` + ```csharp using TUnit.Core; diff --git a/scripts/Verify-DocSnippets.ps1 b/scripts/Verify-DocSnippets.ps1 new file mode 100644 index 00000000000..b755c886617 --- /dev/null +++ b/scripts/Verify-DocSnippets.ps1 @@ -0,0 +1,97 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [string]$PackagesPath, + + [Parameter(Mandatory)] + [string]$Version +) + +$ErrorActionPreference = 'Stop' + +$repositoryRoot = Split-Path $PSScriptRoot -Parent +$resolvedPackagesPath = (Resolve-Path -LiteralPath $PackagesPath).Path +$generatedDirectory = Join-Path $repositoryRoot 'artifacts/doc-tests/generated' +$localPackagesDirectory = Join-Path $generatedDirectory 'packages' +$nugetConfigPath = Join-Path $generatedDirectory 'NuGet.config' +$generatorProjectPath = Join-Path $repositoryRoot 'tools/TUnit.DocSnippetGenerator/TUnit.DocSnippetGenerator.csproj' +$consumerProjectPath = Join-Path $repositoryRoot 'tests/TUnit.DocTests/TUnit.DocTests.csproj' + +$requiredPackages = @( + 'TUnit' + 'TUnit.AspNetCore' + 'TUnit.AspNetCore.Core' + 'TUnit.Aspire' + 'TUnit.Aspire.Core' + 'TUnit.Assertions' + 'TUnit.Assertions.Should' + 'TUnit.Core' + 'TUnit.Engine' + 'TUnit.FsCheck' + 'TUnit.Logging.Microsoft' + 'TUnit.Mocks' + 'TUnit.Mocks.Assertions' + 'TUnit.Mocks.Http' + 'TUnit.Mocks.Logging' + 'TUnit.OpenTelemetry' + 'TUnit.Playwright' +) + +function Get-PackagePath([string]$packageId) +{ + $packageVersion = if ($packageId -eq 'TUnit.Assertions.Should') { "$Version-beta" } else { $Version } + $fileName = "$packageId.$packageVersion.nupkg" + $matches = @(Get-ChildItem -LiteralPath $resolvedPackagesPath -Recurse -File -Filter $fileName) + if ($matches.Count -eq 0) + { + throw "Could not find '$fileName' beneath '$resolvedPackagesPath'." + } + + return $matches[0] +} + +New-Item -ItemType Directory -Force -Path $generatedDirectory | Out-Null +New-Item -ItemType Directory -Force -Path $localPackagesDirectory | Out-Null +Get-ChildItem -LiteralPath $localPackagesDirectory -File -Filter '*.nupkg' | Remove-Item -Force + +foreach ($packageId in $requiredPackages) +{ + Copy-Item -LiteralPath (Get-PackagePath $packageId).FullName -Destination $localPackagesDirectory +} + +& dotnet run --project $generatorProjectPath -c Release -- $repositoryRoot $generatedDirectory +if ($LASTEXITCODE -ne 0) +{ + throw "Documentation snippet generation failed with exit code $LASTEXITCODE." +} + +[IO.File]::WriteAllText( + $nugetConfigPath, + @" + + + + + + + + +"@) + +& dotnet restore $consumerProjectPath --configfile $nugetConfigPath ` + "-p:TUnitPackageVersion=$Version" ` + "-p:TUnitAssertionsShouldPackageVersion=$Version-beta" ` + "-p:GeneratedSnippetsDirectory=$generatedDirectory" +if ($LASTEXITCODE -ne 0) +{ + throw "Documentation snippet restore failed with exit code $LASTEXITCODE." +} + +& dotnet build $consumerProjectPath -c Release --no-restore --nologo '-clp:ErrorsOnly' ` + "-p:TUnitPackageVersion=$Version" ` + "-p:TUnitAssertionsShouldPackageVersion=$Version-beta" ` + "-p:GeneratedSnippetsDirectory=$generatedDirectory" +if ($LASTEXITCODE -ne 0) +{ + throw "Documentation snippet build failed with exit code $LASTEXITCODE." +} diff --git a/tests/TUnit.DocTests/GlobalUsings.cs b/tests/TUnit.DocTests/GlobalUsings.cs new file mode 100644 index 00000000000..5294907a6f8 --- /dev/null +++ b/tests/TUnit.DocTests/GlobalUsings.cs @@ -0,0 +1,44 @@ +global using System; +global using System.Collections; +global using System.Collections.Concurrent; +global using System.Collections.Generic; +global using System.Data; +global using System.Diagnostics; +global using System.Diagnostics.CodeAnalysis; +global using System.Linq; +global using System.Net; +global using System.Net.Http; +global using System.Runtime.CompilerServices; +global using System.Runtime.InteropServices; +global using System.Text.RegularExpressions; +global using System.Threading; +global using System.Threading.Tasks; +global using Microsoft.AspNetCore.Hosting; +global using Microsoft.AspNetCore.Mvc.Testing; +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.Logging; +global using Microsoft.Playwright; +global using TUnit.Assertions; +global using TUnit.Assertions.Attributes; +global using TUnit.Assertions.Core; +global using TUnit.Assertions.Extensions; +global using TUnit.Assertions.Should.Attributes; +global using TUnit.Assertions.Should.Extensions; +global using TUnit.AspNetCore; +global using TUnit.Aspire; +global using TUnit.Core; +global using TUnit.Core.Enums; +global using TUnit.Core.Extensions; +global using TUnit.Core.Interfaces; +global using TUnit.FsCheck; +global using TUnit.Mocks; +global using TUnit.Mocks.Arguments; +global using TUnit.Mocks.Assertions; +global using TUnit.Mocks.Http; +global using TUnit.Mocks.Logging; +global using TUnit.Mocks.Matchers; +global using TUnit.Mocks.Setup; +global using TUnit.Mocks.Verification; +global using TUnit.OpenTelemetry; +global using TUnit.Playwright; +global using TUnit.Core.Executors; diff --git a/tests/TUnit.DocTests/Program.cs b/tests/TUnit.DocTests/Program.cs new file mode 100644 index 00000000000..eb2b6a022df --- /dev/null +++ b/tests/TUnit.DocTests/Program.cs @@ -0,0 +1,21 @@ +namespace TUnit.DocTests; + +#pragma warning disable CS0169, CS0414 + +internal abstract class SnippetContext +{ + protected static readonly CancellationToken CancellationToken = default; + protected static readonly CancellationToken cancellationToken = default; + protected static readonly CancellationToken ct = default; +} + +public sealed class Program +{ + public static void Main() + { + } +} + +internal sealed record User(string Name = "Alice"); + +internal sealed record Person(string Name = "Alice", int Age = 42); diff --git a/tests/TUnit.DocTests/TUnit.DocTests.csproj b/tests/TUnit.DocTests/TUnit.DocTests.csproj new file mode 100644 index 00000000000..27c60112a2b --- /dev/null +++ b/tests/TUnit.DocTests/TUnit.DocTests.csproj @@ -0,0 +1,55 @@ + + + + net10.0 + + Exe + false + false + false + false + false + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/TUnit.DocSnippetGenerator/Program.cs b/tools/TUnit.DocSnippetGenerator/Program.cs new file mode 100644 index 00000000000..588f6203de0 --- /dev/null +++ b/tools/TUnit.DocSnippetGenerator/Program.cs @@ -0,0 +1,469 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +if (args.Length != 2) +{ + Console.Error.WriteLine("Usage: TUnit.DocSnippetGenerator "); + return 1; +} + +var repositoryRoot = Path.GetFullPath(args[0]); +var outputDirectory = Path.GetFullPath(args[1]); +var documents = new[] { Path.Combine(repositoryRoot, "README.md") } + .Concat(Directory.EnumerateFiles(Path.Combine(repositoryRoot, "docs", "docs"), "*.md", SearchOption.AllDirectories)) + .Concat(Directory.EnumerateFiles(Path.Combine(repositoryRoot, "docs", "docs"), "*.mdx", SearchOption.AllDirectories)) + .Order(StringComparer.Ordinal) + .ToArray(); + +var snippets = new List(); +var documentedPackages = new HashSet(StringComparer.OrdinalIgnoreCase); +var contextualSnippets = 0; +var excludedSnippets = 0; +var excludedFiles = 0; + +foreach (var document in documents) +{ + ReadDocument(document); +} + +Directory.CreateDirectory(outputDirectory); +foreach (var oldFile in Directory.EnumerateFiles(outputDirectory, "Snippet*.g.cs")) +{ + File.Delete(oldFile); +} + +var emittedAssemblyAttributes = new HashSet(StringComparer.Ordinal); +for (var index = 0; index < snippets.Count; index++) +{ + File.WriteAllText( + Path.Combine(outputDirectory, $"Snippet{index}.g.cs"), + GenerateSource(snippets[index], index, emittedAssemblyAttributes), + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); +} + +Console.WriteLine($"Generated {snippets.Count} C# documentation snippets."); +Console.WriteLine($"Skipped {contextualSnippets} contextual snippets, {excludedSnippets} explicit snippets, and {excludedFiles} files."); +Console.WriteLine($"Documented TUnit packages: {string.Join(", ", documentedPackages.Order())}"); +return 0; + +void ReadDocument(string documentPath) +{ + var relativePath = Path.GetRelativePath(repositoryRoot, documentPath).Replace('\\', '/'); + var lines = File.ReadAllLines(documentPath); + ReadDocumentedPackages(lines); + var fileIgnoreDirective = lines + .Select(line => Regex.Match(line.Trim(), "^$")) + .FirstOrDefault(match => match.Success); + if (fileIgnoreDirective?.Success == true) + { + excludedFiles++; + Console.WriteLine($"EXCLUDED {relativePath} ({fileIgnoreDirective.Groups[1].Value})"); + return; + } + + var csharpOrdinal = 0; + + for (var lineIndex = 0; lineIndex < lines.Length; lineIndex++) + { + if (Regex.IsMatch(lines[lineIndex], "^```csharp\\s*$")) + { + csharpOrdinal++; + var startLine = lineIndex + 2; + var body = new List(); + for (lineIndex++; lineIndex < lines.Length && !Regex.IsMatch(lines[lineIndex], "^```\\s*$"); lineIndex++) + { + body.Add(lines[lineIndex]); + } + + if (lineIndex >= lines.Length) + { + throw new InvalidOperationException($"Unclosed C# fence at {relativePath}:{startLine}."); + } + + var directive = startLine >= 3 ? lines[startLine - 3].Trim() : string.Empty; + var ignoreMatch = Regex.Match(directive, "^$"); + if (directive.StartsWith("$"); + var splitMode = Regex.Match(directive, "^$"); + if (directive.StartsWith(" ``` -Use `` for a page whose examples share application-specific context. Ignore directives require a reason. Run the check against local packages with: +Use `` when a page's member and statement fragments depend on surrounding prose; full declarations still compile, and explicit member or statement directives opt individual fragments back in. Use `` when no snippets on a page can compile independently. These directives require a reason. + +Run the check against local packages with: ```powershell ./scripts/Verify-DocSnippets.ps1 -PackagesPath -Version diff --git a/README.md b/README.md index 069189a44d0..1ba275bd68d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ ![TUnit](assets/banner.png) + + # TUnit A modern .NET testing framework. Tests are discovered at compile time via source generators, run in parallel by default, and work under Native AOT — all built on [Microsoft.Testing.Platform](https://learn.microsoft.com/en-us/dotnet/core/testing/microsoft-testing-platform-intro). diff --git a/docs/docs/assertions/awaiting.md b/docs/docs/assertions/awaiting.md index ffbb4c98410..78dab0cdbba 100644 --- a/docs/docs/assertions/awaiting.md +++ b/docs/docs/assertions/awaiting.md @@ -2,6 +2,8 @@ sidebar_position: 1 --- + + # Awaiting In TUnit you `await` your assertions, and this serves two purposes: diff --git a/docs/docs/assertions/boolean.md b/docs/docs/assertions/boolean.md index 6140d9e5e4c..6ac87499839 100644 --- a/docs/docs/assertions/boolean.md +++ b/docs/docs/assertions/boolean.md @@ -2,6 +2,8 @@ sidebar_position: 3.5 --- + + # Boolean Assertions TUnit provides simple, expressive assertions for testing boolean values. These assertions work with both `bool` and `bool?` (nullable boolean) types. diff --git a/docs/docs/assertions/collections.md b/docs/docs/assertions/collections.md index b22be27ad95..8c2283ecd3c 100644 --- a/docs/docs/assertions/collections.md +++ b/docs/docs/assertions/collections.md @@ -2,6 +2,8 @@ sidebar_position: 6.5 --- + + # Collection Assertions TUnit provides comprehensive assertions for testing collections, including membership, count, ordering, and equivalency checks. These assertions work with any `IEnumerable`. diff --git a/docs/docs/assertions/combining-assertions.md b/docs/docs/assertions/combining-assertions.md index fd071ded015..caa5d3b5d99 100644 --- a/docs/docs/assertions/combining-assertions.md +++ b/docs/docs/assertions/combining-assertions.md @@ -2,6 +2,8 @@ sidebar_position: 11 --- + + # Combining Assertions TUnit provides several ways to combine multiple assertions within a single test: chaining with `.And` and `.Or`, and grouping with `Assert.Multiple()`. diff --git a/docs/docs/assertions/datetime.md b/docs/docs/assertions/datetime.md index dd4274864e6..c1a750c2164 100644 --- a/docs/docs/assertions/datetime.md +++ b/docs/docs/assertions/datetime.md @@ -2,6 +2,8 @@ sidebar_position: 7.5 --- + + # DateTime and Time Assertions TUnit provides comprehensive assertions for date and time types, including `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, and `TimeSpan`, with support for tolerance-based comparisons and specialized checks. diff --git a/docs/docs/assertions/dictionaries.md b/docs/docs/assertions/dictionaries.md index 113851d507c..444b12c241c 100644 --- a/docs/docs/assertions/dictionaries.md +++ b/docs/docs/assertions/dictionaries.md @@ -2,6 +2,8 @@ sidebar_position: 6.8 --- + + # Dictionary Assertions TUnit provides specialized assertions for testing dictionaries (`IReadOnlyDictionary`), including key and value membership checks. Dictionaries also inherit all collection assertions. diff --git a/docs/docs/assertions/equality-and-comparison.md b/docs/docs/assertions/equality-and-comparison.md index faf0808e900..4b45d5ac524 100644 --- a/docs/docs/assertions/equality-and-comparison.md +++ b/docs/docs/assertions/equality-and-comparison.md @@ -2,6 +2,8 @@ sidebar_position: 2 --- + + # Equality and Comparison Assertions TUnit provides comprehensive assertions for testing equality and comparing values. These assertions work with any type that implements the appropriate comparison interfaces. diff --git a/docs/docs/assertions/exceptions.md b/docs/docs/assertions/exceptions.md index 5c6683b3042..413e3d7e01c 100644 --- a/docs/docs/assertions/exceptions.md +++ b/docs/docs/assertions/exceptions.md @@ -2,6 +2,8 @@ sidebar_position: 8 --- + + # Exception Assertions TUnit provides comprehensive assertions for testing that code throws (or doesn't throw) exceptions, with rich support for validating exception types, messages, and properties. diff --git a/docs/docs/assertions/getting-started.md b/docs/docs/assertions/getting-started.md index 4c97656b4d2..946e03597b2 100644 --- a/docs/docs/assertions/getting-started.md +++ b/docs/docs/assertions/getting-started.md @@ -2,6 +2,8 @@ sidebar_position: 1 --- + + # Getting Started with Assertions TUnit provides a comprehensive, fluent assertion library that makes your tests readable and expressive. This guide introduces the core concepts and gets you started with writing assertions. diff --git a/docs/docs/assertions/member-assertions.md b/docs/docs/assertions/member-assertions.md index a1b8b34d4cf..cca3add44bf 100644 --- a/docs/docs/assertions/member-assertions.md +++ b/docs/docs/assertions/member-assertions.md @@ -2,6 +2,8 @@ sidebar_position: 12 --- + + # Member Assertions The `.Member()` method allows you to assert on object properties while maintaining the parent object's context for chaining. This is useful when you need to validate multiple properties of the same object. diff --git a/docs/docs/assertions/null-and-default.md b/docs/docs/assertions/null-and-default.md index 0facb49a168..6617ebc8b59 100644 --- a/docs/docs/assertions/null-and-default.md +++ b/docs/docs/assertions/null-and-default.md @@ -2,6 +2,8 @@ sidebar_position: 2.5 --- + + # Null and Default Value Assertions TUnit provides assertions for testing null values and default values. These assertions integrate with C#'s nullability annotations to provide better compile-time safety. diff --git a/docs/docs/assertions/numeric.md b/docs/docs/assertions/numeric.md index 1f012780543..cdf2292c95c 100644 --- a/docs/docs/assertions/numeric.md +++ b/docs/docs/assertions/numeric.md @@ -2,6 +2,8 @@ sidebar_position: 4.5 --- + + # Numeric Assertions TUnit provides comprehensive assertions for testing numeric values, including specialized assertions for positive/negative values and comparison assertions with tolerance support. diff --git a/docs/docs/assertions/regex-assertions.md b/docs/docs/assertions/regex-assertions.md index 139ae3703d2..bbc8f9a70d1 100644 --- a/docs/docs/assertions/regex-assertions.md +++ b/docs/docs/assertions/regex-assertions.md @@ -2,6 +2,8 @@ sidebar_position: 13 --- + + # Regex Assertions The `.Matches()` method allows you to validate strings against regular expressions and assert on capture groups, match positions, and match lengths. This is useful when you need to validate structured text like emails, phone numbers, dates, or extract specific parts of a string. diff --git a/docs/docs/assertions/specialized-types.md b/docs/docs/assertions/specialized-types.md index 6cefde9117c..ac9bc051eca 100644 --- a/docs/docs/assertions/specialized-types.md +++ b/docs/docs/assertions/specialized-types.md @@ -2,6 +2,8 @@ sidebar_position: 12 --- + + # Specialized Type Assertions TUnit provides assertions for many specialized .NET types beyond the common primitives. This page covers GUID, HTTP, file system, networking, and other specialized assertions. diff --git a/docs/docs/assertions/string.md b/docs/docs/assertions/string.md index 6d9336f4a08..0844ab43742 100644 --- a/docs/docs/assertions/string.md +++ b/docs/docs/assertions/string.md @@ -2,6 +2,8 @@ sidebar_position: 5.5 --- + + # String Assertions TUnit provides rich assertions for testing strings, including substring matching, pattern matching, length checks, and various string comparison options. diff --git a/docs/docs/assertions/tasks-and-async.md b/docs/docs/assertions/tasks-and-async.md index cbf0e94e779..3a7bd6f6536 100644 --- a/docs/docs/assertions/tasks-and-async.md +++ b/docs/docs/assertions/tasks-and-async.md @@ -2,6 +2,8 @@ sidebar_position: 11 --- + + # Task and Async Assertions TUnit provides specialized assertions for testing `Task` and `Task` objects, including state checking, completion timeouts, and async exception handling. diff --git a/docs/docs/assertions/type-checking.md b/docs/docs/assertions/type-checking.md index 07fe2038bf5..d47f64e4932 100644 --- a/docs/docs/assertions/type-checking.md +++ b/docs/docs/assertions/type-checking.md @@ -2,6 +2,8 @@ sidebar_position: 5 --- + + # Type Checking TUnit assertions check types at compile time wherever possible. This gives faster feedback and catches mistakes before your build pipeline runs. diff --git a/docs/docs/assertions/types.md b/docs/docs/assertions/types.md index bffcf9b0ed9..b84aed5ff53 100644 --- a/docs/docs/assertions/types.md +++ b/docs/docs/assertions/types.md @@ -2,6 +2,8 @@ sidebar_position: 9 --- + + # Type Assertions TUnit provides comprehensive assertions for testing types and type properties. These assertions work with both runtime values and `Type` objects themselves. diff --git a/docs/docs/benchmarks/methodology.md b/docs/docs/benchmarks/methodology.md index 102c5fa47bf..790ee77072b 100644 --- a/docs/docs/benchmarks/methodology.md +++ b/docs/docs/benchmarks/methodology.md @@ -4,6 +4,8 @@ description: How TUnit's performance benchmarks are measured and compared sidebar_position: 2 --- + + # Benchmark Methodology This page explains how TUnit's performance benchmarks are conducted to ensure fair, accurate, and reproducible results. diff --git a/docs/docs/comparison/framework-differences.md b/docs/docs/comparison/framework-differences.md index 0cd6bb260c2..91663b7d901 100644 --- a/docs/docs/comparison/framework-differences.md +++ b/docs/docs/comparison/framework-differences.md @@ -1,3 +1,5 @@ + + # Framework Differences TUnit is inspired by NUnit and xUnit — they're excellent frameworks that have served the .NET community well. TUnit was built to address some pain points around parallelism, lifecycle hooks, test isolation, and extensibility. diff --git a/docs/docs/execution/cancellation.md b/docs/docs/execution/cancellation.md index 03fb199b24f..e89e3fb6698 100644 --- a/docs/docs/execution/cancellation.md +++ b/docs/docs/execution/cancellation.md @@ -1,3 +1,5 @@ + + # Cancelling a Test Call `TestContext.Execution.Cancel()` to request cooperative cancellation of the current test without affecting other tests or the test session: diff --git a/docs/docs/execution/parameters.md b/docs/docs/execution/parameters.md index 2695f4bd230..73c6febee68 100644 --- a/docs/docs/execution/parameters.md +++ b/docs/docs/execution/parameters.md @@ -1,3 +1,5 @@ + + # Test Parameters TUnit allows you to pass custom key-value parameters to your tests at runtime using the `--test-parameter` command-line option. These parameters are accessible via `TestContext.Parameters`. diff --git a/docs/docs/execution/timeouts.md b/docs/docs/execution/timeouts.md index af60dd639f2..f00ef2e0b56 100644 --- a/docs/docs/execution/timeouts.md +++ b/docs/docs/execution/timeouts.md @@ -2,6 +2,8 @@ sidebar_position: 5 --- + + # Timeouts If you want to stop a test after a specified amount of time, add a `[Timeout]` attribute onto your test method or class. This takes an `int` of how many milliseconds a test can execute for. diff --git a/docs/docs/extending/exception-handling.md b/docs/docs/extending/exception-handling.md index 66fe0fb5dfc..df164b06322 100644 --- a/docs/docs/extending/exception-handling.md +++ b/docs/docs/extending/exception-handling.md @@ -1,3 +1,5 @@ + + # Exception Handling When a test fails, TUnit throws an exception. Most of the time you don't need to think about this — the framework handles it and reports the failure. But there are a couple of exception types you might want to throw yourself. diff --git a/docs/docs/getting-started/writing-your-first-test.md b/docs/docs/getting-started/writing-your-first-test.md index 0cc33868902..3c34ee9bc80 100644 --- a/docs/docs/getting-started/writing-your-first-test.md +++ b/docs/docs/getting-started/writing-your-first-test.md @@ -1,3 +1,5 @@ + + # Writing your first test ## Quick Start: Complete Example diff --git a/docs/docs/guides/distributed-tracing.md b/docs/docs/guides/distributed-tracing.md index 8566705305b..c78ec0a2bbe 100644 --- a/docs/docs/guides/distributed-tracing.md +++ b/docs/docs/guides/distributed-tracing.md @@ -2,6 +2,8 @@ sidebar_position: 20 --- + + # Distributed Tracing This page is for users wiring TUnit up to a tracing backend like Seq, Jaeger, Tempo, or the Aspire dashboard. If you just want a working setup, start with [OpenTelemetry Tracing](/docs/examples/opentelemetry). If you're hitting problems, jump straight to its [Troubleshooting](/docs/examples/opentelemetry#troubleshooting) section. diff --git a/docs/docs/guides/html-report.md b/docs/docs/guides/html-report.md index 8353076e1de..4539d079221 100644 --- a/docs/docs/guides/html-report.md +++ b/docs/docs/guides/html-report.md @@ -2,6 +2,8 @@ sidebar_position: 10 --- + + # HTML Test Report TUnit automatically generates a rich HTML test report after every test run. No configuration is needed — the report is always on by default. diff --git a/docs/docs/guides/philosophy.md b/docs/docs/guides/philosophy.md index 2dea84ad86d..1c8538309f9 100644 --- a/docs/docs/guides/philosophy.md +++ b/docs/docs/guides/philosophy.md @@ -1,3 +1,5 @@ + + # Philosophy TUnit does some things differently from other .NET testing frameworks. This page explains the thinking behind those choices. diff --git a/docs/docs/reference/programmatic-configuration.md b/docs/docs/reference/programmatic-configuration.md index d2c9bb70d8c..541d36ee129 100644 --- a/docs/docs/reference/programmatic-configuration.md +++ b/docs/docs/reference/programmatic-configuration.md @@ -2,6 +2,8 @@ sidebar_position: 4 --- + + # Programmatic Configuration ## Overview diff --git a/docs/docs/writing-tests/artifacts.md b/docs/docs/writing-tests/artifacts.md index ebc7595e423..edb507f92bf 100644 --- a/docs/docs/writing-tests/artifacts.md +++ b/docs/docs/writing-tests/artifacts.md @@ -1,3 +1,5 @@ + + # Test Artifacts Test artifacts are files (screenshots, logs, videos, JSON dumps, etc.) that you can attach to your tests. They are invaluable for debugging test failures, especially in integration tests and end-to-end tests. diff --git a/docs/docs/writing-tests/hooks.md b/docs/docs/writing-tests/hooks.md index 4eb39e9d8fa..8ac34b10d13 100644 --- a/docs/docs/writing-tests/hooks.md +++ b/docs/docs/writing-tests/hooks.md @@ -1,3 +1,5 @@ + + # Hooks Hooks let you run code at specific points in the test lifecycle using `[Before]` / `[BeforeEvery]` and `[After]` / `[AfterEvery]` attributes. Most simple setup belongs in the constructor; use hooks for async operations or shared resource management. diff --git a/docs/docs/writing-tests/mocking/http.md b/docs/docs/writing-tests/mocking/http.md index c2cc9bf42e1..c87387dc397 100644 --- a/docs/docs/writing-tests/mocking/http.md +++ b/docs/docs/writing-tests/mocking/http.md @@ -2,6 +2,8 @@ sidebar_position: 6 --- + + # HTTP Mocking `TUnit.Mocks.Http` provides `MockHttpHandler` — a drop-in `HttpMessageHandler` replacement for testing code that uses `HttpClient`. diff --git a/docs/docs/writing-tests/mocking/index.md b/docs/docs/writing-tests/mocking/index.md index e302a95fe93..58ab6f8d9f2 100644 --- a/docs/docs/writing-tests/mocking/index.md +++ b/docs/docs/writing-tests/mocking/index.md @@ -2,6 +2,8 @@ sidebar_position: 1 --- + + # TUnit.Mocks TUnit.Mocks is a **source-generated, AOT-compatible** mocking framework. Because mocks are generated at compile time, it works with Native AOT, trimming, and single-file publishing — unlike traditional mocking libraries that rely on runtime proxy generation. diff --git a/docs/docs/writing-tests/mocking/logging.md b/docs/docs/writing-tests/mocking/logging.md index 7c6d1460267..1a787d68d12 100644 --- a/docs/docs/writing-tests/mocking/logging.md +++ b/docs/docs/writing-tests/mocking/logging.md @@ -2,6 +2,8 @@ sidebar_position: 7 --- + + # Logging `TUnit.Mocks.Logging` provides `MockLogger` — a simple `ILogger` implementation that captures log entries for inspection and verification. diff --git a/docs/docs/writing-tests/mocking/setup.md b/docs/docs/writing-tests/mocking/setup.md index 353df93f258..56d9f1860a8 100644 --- a/docs/docs/writing-tests/mocking/setup.md +++ b/docs/docs/writing-tests/mocking/setup.md @@ -2,6 +2,8 @@ sidebar_position: 2 --- + + # Setup & Stubbing Methods are called directly on `Mock` — the chain method (`.Returns()`, `.Throws()`, etc.) makes it a setup. diff --git a/docs/docs/writing-tests/mocking/verification.md b/docs/docs/writing-tests/mocking/verification.md index 6ffd665364b..13d3b508095 100644 --- a/docs/docs/writing-tests/mocking/verification.md +++ b/docs/docs/writing-tests/mocking/verification.md @@ -2,6 +2,8 @@ sidebar_position: 3 --- + + # Verification Verification uses the same methods as setup — the chain method (`.WasCalled()`, `.WasNeverCalled()`) makes it a verification instead of a setup. diff --git a/docs/docs/writing-tests/ordering.md b/docs/docs/writing-tests/ordering.md index b09d8778060..3fa37c9823f 100644 --- a/docs/docs/writing-tests/ordering.md +++ b/docs/docs/writing-tests/ordering.md @@ -1,3 +1,5 @@ + + # Test Ordering & Dependencies ## Ordering with [Order] diff --git a/tools/TUnit.DocSnippetGenerator/Program.cs b/tools/TUnit.DocSnippetGenerator/Program.cs index 588f6203de0..c45d72311cc 100644 --- a/tools/TUnit.DocSnippetGenerator/Program.cs +++ b/tools/TUnit.DocSnippetGenerator/Program.cs @@ -25,6 +25,7 @@ var snippets = new List(); var documentedPackages = new HashSet(StringComparer.OrdinalIgnoreCase); var contextualSnippets = 0; +var contextualFiles = new HashSet(StringComparer.Ordinal); var excludedSnippets = 0; var excludedFiles = 0; @@ -49,7 +50,7 @@ } Console.WriteLine($"Generated {snippets.Count} C# documentation snippets."); -Console.WriteLine($"Skipped {contextualSnippets} contextual snippets, {excludedSnippets} explicit snippets, and {excludedFiles} files."); +Console.WriteLine($"Skipped {contextualSnippets} snippets declared contextual by {contextualFiles.Count} files, {excludedSnippets} explicit snippets, and {excludedFiles} files."); Console.WriteLine($"Documented TUnit packages: {string.Join(", ", documentedPackages.Order())}"); return 0; @@ -68,18 +69,32 @@ void ReadDocument(string documentPath) return; } + var contextualFileDirective = lines + .Select(line => Regex.Match(line.Trim(), "^$")) + .FirstOrDefault(match => match.Success); + if (lines.Any(line => line.Trim().StartsWith(" + ``` -Use `` when a page's member and statement fragments depend on surrounding prose; full declarations still compile, and explicit member or statement directives opt individual fragments back in. Use `` when no snippets on a page can compile independently. These directives require a reason. +Use `` on each fence that depends on surrounding prose. Its page must declare ``, so unmarked fences still compile and cannot be silently excluded by page-level configuration. Use `` when no snippets on a page can compile independently. File directives require a reason. Run the check against local packages with: diff --git a/README.md b/README.md index 1ba275bd68d..86747c0d2dc 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ A modern .NET testing framework. Tests are discovered at compile time via source ## What it looks like + ```csharp [Test] [Arguments("GOLD", 100.00, 80.00)] @@ -96,6 +97,7 @@ dotnet add package TUnit ### Data-driven tests + ```csharp [Test] [Arguments("user1@test.com", "ValidPassword123")] @@ -116,6 +118,7 @@ Need more? `[MethodDataSource]` pulls rows from a method, and custom `DataSource Assertions are async, chainable, and produce the focused failure messages shown above: + ```csharp await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK) .Because("the health endpoint should always be up"); @@ -164,6 +167,7 @@ Property injection keeps base test classes clean — subclasses inherit the fixt Everything runs in parallel by default. Opt out or sequence tests where it matters: + ```csharp [Test] public async Task Register_User() { ... } @@ -180,6 +184,7 @@ public async Task Migrates_Schema() { ... } ### Lifecycle hooks at every scope + ```csharp [Before(Test)] // also: Class, Assembly, TestSession public async Task SetUp() { ... } @@ -192,6 +197,7 @@ public static async Task TearDownDatabase(ClassHookContext context) { ... } `TUnit.Mocks` is a source-generated, Native AOT-compatible mocking library — no runtime proxies, no `Castle.Core`. It works with any test framework: + ```csharp var gateway = IPaymentGateway.Mock(); // or Mock.Of() @@ -205,6 +211,7 @@ gateway.ChargeAsync(99.99m).WasCalled(Times.Once); Companion packages mock the annoying stuff for you: + ```csharp // TUnit.Mocks.Http — a real HttpClient backed by a scriptable handler using var client = Mock.HttpClient("https://api.example.com"); @@ -219,6 +226,7 @@ logger.VerifyLog().AtLevel(LogLevel.Warning).ContainingMessage("retrying").WasCa Extend built-in base classes to create your own skip conditions, retry logic, and more: + ```csharp public class WindowsOnlyAttribute : SkipAttribute { @@ -294,6 +302,7 @@ public class HomePageTests : PageTest ### Property-based testing (FsCheck) + ```csharp [Test, FsCheckProperty] public bool Reversing_Twice_Returns_Original(int[] array) => diff --git a/docs/docs/assertions/awaiting.md b/docs/docs/assertions/awaiting.md index 78dab0cdbba..0ca0c7457a5 100644 --- a/docs/docs/assertions/awaiting.md +++ b/docs/docs/assertions/awaiting.md @@ -17,6 +17,7 @@ If you forget to `await`, your assertion will not actually be executed, and your This will error: + ```csharp [Test] public void MyTest() @@ -29,6 +30,7 @@ This will error: This won't: + ```csharp [Test] public async Task MyTest() @@ -48,6 +50,7 @@ When you `await` an assertion in TUnit, it returns a reference to the subject th ### Type Casting with Confidence + ```csharp [Test] public async Task CastAndUseSpecificType() @@ -71,6 +74,7 @@ public async Task CastAndUseSpecificType() You can chain multiple assertions together for more complex validations: + ```csharp [Test] public async Task ComplexObjectValidation() @@ -88,6 +92,7 @@ public async Task ComplexObjectValidation() ### Collection Assertions with Complex Conditions + ```csharp [Test] public async Task ComplexCollectionAssertions() @@ -111,6 +116,7 @@ public async Task ComplexCollectionAssertions() ### Async Operation Assertions + ```csharp [Test] public async Task AsyncOperationAssertions() @@ -132,6 +138,7 @@ public async Task AsyncOperationAssertions() ### Exception Assertions with Details + ```csharp [Test] public async Task DetailedExceptionAssertions() @@ -159,6 +166,7 @@ public async Task DetailedExceptionAssertions() ### Custom Assertion Conditions + ```csharp [Test] public async Task CustomAssertionConditions() @@ -183,6 +191,7 @@ public async Task CustomAssertionConditions() ### Combining Or and And Conditions + ```csharp [Test] public async Task ComplexLogicalConditions() diff --git a/docs/docs/assertions/boolean.md b/docs/docs/assertions/boolean.md index 6ac87499839..f1f87a2540d 100644 --- a/docs/docs/assertions/boolean.md +++ b/docs/docs/assertions/boolean.md @@ -14,6 +14,7 @@ TUnit provides simple, expressive assertions for testing boolean values. These a Tests that a boolean value is `true`: + ```csharp [Test] public async Task Value_Is_True() @@ -30,6 +31,7 @@ public async Task Value_Is_True() Tests that a boolean value is `false`: + ```csharp [Test] public async Task Value_Is_False() @@ -46,6 +48,7 @@ public async Task Value_Is_False() You can also use `IsEqualTo()` for boolean comparisons: + ```csharp [Test] public async Task Using_IsEqualTo() @@ -66,6 +69,7 @@ However, `IsTrue()` and `IsFalse()` are more expressive and recommended for bool Both assertions work with nullable booleans (`bool?`): + ```csharp [Test] public async Task Nullable_Boolean_True() @@ -94,6 +98,7 @@ public async Task Nullable_Boolean_False() If a nullable boolean is `null`, both `IsTrue()` and `IsFalse()` will fail: + ```csharp [Test] public async Task Nullable_Boolean_Null() @@ -113,6 +118,7 @@ public async Task Nullable_Boolean_Null() Boolean assertions can be chained with other assertions: + ```csharp [Test] public async Task Chained_With_Other_Assertions() @@ -129,6 +135,7 @@ public async Task Chained_With_Other_Assertions() ### Validation Results + ```csharp [Test] public async Task Email_Validation() @@ -143,6 +150,7 @@ public async Task Email_Validation() ### Permission Checks + ```csharp [Test] public async Task User_Permissions() @@ -157,6 +165,7 @@ public async Task User_Permissions() ### State Flags + ```csharp [Test] public async Task Service_State() @@ -173,6 +182,7 @@ public async Task Service_State() ### Feature Flags + ```csharp [Test] public async Task Feature_Toggles() @@ -188,6 +198,7 @@ public async Task Feature_Toggles() When testing the boolean result of a comparison, use the specific assertion instead for clearer failure messages: + ```csharp [Test] public async Task Prefer_Specific_Assertions() diff --git a/docs/docs/assertions/collections.md b/docs/docs/assertions/collections.md index 8c2283ecd3c..d6636f366fe 100644 --- a/docs/docs/assertions/collections.md +++ b/docs/docs/assertions/collections.md @@ -14,6 +14,7 @@ TUnit provides comprehensive assertions for testing collections, including membe Tests that a collection contains a specific item: + ```csharp [Test] public async Task Collection_Contains_Item() @@ -27,6 +28,7 @@ public async Task Collection_Contains_Item() Works with any collection type: + ```csharp [Test] public async Task Various_Collection_Types() @@ -46,6 +48,7 @@ public async Task Various_Collection_Types() Tests that a collection contains an item matching a predicate, and returns that item: + ```csharp [Test] public async Task Collection_Contains_Matching_Item() @@ -68,6 +71,7 @@ public async Task Collection_Contains_Matching_Item() Tests that a collection does not contain a specific item: + ```csharp [Test] public async Task Collection_Does_Not_Contain() @@ -83,6 +87,7 @@ public async Task Collection_Does_Not_Contain() Tests that no items match the predicate: + ```csharp [Test] public async Task Collection_Does_Not_Contain_Matching() @@ -104,6 +109,7 @@ public async Task Collection_Does_Not_Contain_Matching() Tests that a collection has an exact count: + ```csharp [Test] public async Task Collection_Has_Count() @@ -118,6 +124,7 @@ public async Task Collection_Has_Count() Get the count for further assertions: + ```csharp [Test] public async Task Count_With_Comparison() @@ -137,6 +144,7 @@ public async Task Count_With_Comparison() Count items that satisfy an assertion, allowing you to reuse existing assertion methods: + ```csharp [Test] public async Task Count_With_Inner_Assertion() @@ -170,6 +178,7 @@ public async Task Count_Strings_With_Inner_Assertion() Count assertions preserve the collection type, allowing you to chain additional collection assertions: + ```csharp [Test] public async Task Count_With_Chaining() @@ -200,6 +209,7 @@ public async Task Count_With_Chaining() Tests that a collection has no items: + ```csharp [Test] public async Task Collection_Is_Empty() @@ -215,6 +225,7 @@ public async Task Collection_Is_Empty() Tests that a collection has at least one item: + ```csharp [Test] public async Task Collection_Is_Not_Empty() @@ -229,6 +240,7 @@ public async Task Collection_Is_Not_Empty() Tests that a collection has exactly one item, and returns that item: + ```csharp [Test] public async Task Collection_Has_Single_Item() @@ -243,6 +255,7 @@ public async Task Collection_Has_Single_Item() Use `.Item` to continue assertions directly against the single item: + ```csharp await Assert.That(users) .HasSingleItem() @@ -255,6 +268,7 @@ await Assert.That(users) Tests that a collection is sorted in ascending order: + ```csharp [Test] public async Task Collection_In_Ascending_Order() @@ -265,6 +279,7 @@ public async Task Collection_In_Ascending_Order() } ``` + ```csharp [Test] public async Task Strings_In_Order() @@ -279,6 +294,7 @@ public async Task Strings_In_Order() Tests that a collection is sorted in descending order: + ```csharp [Test] public async Task Collection_In_Descending_Order() @@ -293,6 +309,7 @@ public async Task Collection_In_Descending_Order() Tests that a collection is ordered by a specific property: + ```csharp [Test] public async Task Ordered_By_Property() @@ -312,6 +329,7 @@ public async Task Ordered_By_Property() Tests that a collection is ordered by a property in descending order: + ```csharp [Test] public async Task Ordered_By_Descending() @@ -333,6 +351,7 @@ public async Task Ordered_By_Descending() Tests that all items satisfy a condition: + ```csharp [Test] public async Task All_Items_Match() @@ -347,6 +366,7 @@ public async Task All_Items_Match() The single parameter overload will match T from `IEnumerable` - Giving you the relevant assertions for that type. + ```csharp [Test] public async Task All_Satisfy_With_Property() @@ -366,6 +386,7 @@ public async Task All_Satisfy_With_Property() You can also map to other types by accessing properties an such - And then assert on those specific values: + ```csharp [Test] public async Task All_Satisfy_With_Mapper() @@ -389,6 +410,7 @@ public async Task All_Satisfy_With_Mapper() Tests that at least one item satisfies a condition: + ```csharp [Test] public async Task Any_Item_Matches() @@ -407,6 +429,7 @@ Collection equivalency checks whether two collections contain the same elements. Tests that two collections contain the same items. By default, order is ignored (use `CollectionOrdering.Matching` to require matching order): + ```csharp [Test] public async Task Collections_Are_Equivalent() @@ -420,6 +443,7 @@ public async Task Collections_Are_Equivalent() Different collection types: + ```csharp [Test] public async Task Different_Collection_Types() @@ -433,6 +457,7 @@ public async Task Different_Collection_Types() #### With Custom Comparer + ```csharp [Test] public async Task Equivalent_With_Comparer() @@ -448,6 +473,7 @@ public async Task Equivalent_With_Comparer() #### With Custom Equality Predicate + ```csharp [Test] public async Task Equivalent_With_Predicate() @@ -474,6 +500,7 @@ public async Task Equivalent_With_Predicate() By default, `IsEquivalentTo` ignores the order of elements: + ```csharp [Test] public async Task Equivalent_Ignoring_Order() @@ -490,6 +517,7 @@ public async Task Equivalent_Ignoring_Order() To require elements to be in the same order, pass `CollectionOrdering.Matching`: + ```csharp [Test] public async Task Equivalent_With_Matching_Order() @@ -503,6 +531,7 @@ public async Task Equivalent_With_Matching_Order() This will fail if elements are in different positions: + ```csharp [Test] public async Task Not_Equivalent_Different_Order() @@ -519,6 +548,7 @@ public async Task Not_Equivalent_Different_Order() Tests that collections are not equivalent: + ```csharp [Test] public async Task Collections_Not_Equivalent() @@ -540,6 +570,7 @@ The default behavior (ignoring order) is ideal for: - Checking API responses where element order doesn't matter - Testing collection transformations that may reorder elements + ```csharp [Test] public async Task Database_Query_Results() @@ -560,6 +591,7 @@ Use order-sensitive comparison when: - Checking sequences where position matters - Testing priority queues or ordered data structures + ```csharp [Test] public async Task Sorted_Query_Results() @@ -579,6 +611,7 @@ public async Task Sorted_Query_Results() If you need multiple order-sensitive assertions in the same test, consider extracting a helper or being explicit: + ```csharp [Test] public async Task Multiple_Order_Sensitive_Checks() @@ -594,6 +627,7 @@ public async Task Multiple_Order_Sensitive_Checks() For ordered comparisons, you can also use `IsInOrder()`: + ```csharp [Test] public async Task Verify_Ordering_Separately() @@ -612,6 +646,7 @@ public async Task Verify_Ordering_Separately() ### Deep Comparison with IsEquivalentTo + ```csharp [Test] public async Task Structurally_Equal() @@ -634,6 +669,7 @@ public async Task Structurally_Equal() ### IsNotEquivalentTo for Deep Comparison + ```csharp [Test] public async Task Not_Structurally_Equal() @@ -658,6 +694,7 @@ public async Task Not_Structurally_Equal() Tests that all items in a collection are unique: + ```csharp [Test] public async Task All_Items_Distinct() @@ -670,6 +707,7 @@ public async Task All_Items_Distinct() Fails if duplicates exist: + ```csharp [Test] public async Task Duplicates_Fail() @@ -685,6 +723,7 @@ public async Task Duplicates_Fail() ### Filtering Results + ```csharp [Test] public async Task Filter_And_Assert() @@ -700,6 +739,7 @@ public async Task Filter_And_Assert() ### LINQ Query Results + ```csharp [Test] public async Task LINQ_Query_Results() @@ -721,6 +761,7 @@ public async Task LINQ_Query_Results() ### Sorting Validation + ```csharp [Test] public async Task Verify_Sorting() @@ -735,6 +776,7 @@ public async Task Verify_Sorting() ### API Response Validation + ```csharp [Test] public async Task API_Returns_Expected_Items() @@ -750,6 +792,7 @@ public async Task API_Returns_Expected_Items() ### Collection Transformation + ```csharp [Test] public async Task Map_And_Verify() @@ -772,6 +815,7 @@ public async Task Map_And_Verify() ## Empty vs Null Collections + ```csharp [Test] public async Task Empty_vs_Null() @@ -789,6 +833,7 @@ public async Task Empty_vs_Null() ## Nested Collections + ```csharp [Test] public async Task Nested_Collections() @@ -811,6 +856,7 @@ public async Task Nested_Collections() ## Chaining Collection Assertions + ```csharp [Test] public async Task Chained_Collection_Assertions() @@ -832,6 +878,7 @@ public async Task Chained_Collection_Assertions() ### Materialize IEnumerable + ```csharp [Test] public async Task Materialize_Before_Multiple_Assertions() @@ -851,6 +898,7 @@ public async Task Materialize_Before_Multiple_Assertions() ## Working with HashSet and SortedSet + ```csharp [Test] public async Task HashSet_Assertions() @@ -878,6 +926,7 @@ public async Task SortedSet_Assertions() ### Validate All Items + ```csharp [Test] public async Task Validate_Each_Item() @@ -897,6 +946,7 @@ public async Task Validate_Each_Item() Or more elegantly: + ```csharp [Test] public async Task Validate_All_With_Assertion() diff --git a/docs/docs/assertions/combining-assertions.md b/docs/docs/assertions/combining-assertions.md index caa5d3b5d99..a3a598ee027 100644 --- a/docs/docs/assertions/combining-assertions.md +++ b/docs/docs/assertions/combining-assertions.md @@ -12,6 +12,7 @@ TUnit provides several ways to combine multiple assertions within a single test: Use the `.And` property to chain multiple conditions on the same value. Every condition must pass for the assertion to succeed. This reads naturally and avoids repeating `Assert.That(...)` for each check. + ```csharp [Test] public async Task MyTest() @@ -29,6 +30,7 @@ public async Task MyTest() Use the `.Or` property when at least one condition must pass. This is useful for values that are valid across a known set of outcomes. + ```csharp [Test] public async Task MyTest() @@ -45,6 +47,7 @@ public async Task MyTest() :::warning Mixing And/Or is not supported `.And` and `.Or` cannot be mixed in a single chain. Attempting to use `.Or` after `.And` (or vice versa) throws `MixedAndOrAssertionsException` at runtime. If you need both kinds of logic, split the chain across multiple `Assert.That(...)` calls, or combine the conditions into a single boolean expression beforehand. + ```csharp // NOT supported - throws MixedAndOrAssertionsException at runtime await Assert.That(result) @@ -65,6 +68,7 @@ By default, a failing assertion throws immediately and stops the test. `Assert.M Implicit scope (covers the rest of the method): + ```csharp [Test] public async Task MyTest() @@ -80,6 +84,7 @@ public async Task MyTest() Explicit scope (covers only the block): + ```csharp [Test] public async Task MyTest() diff --git a/docs/docs/assertions/datetime.md b/docs/docs/assertions/datetime.md index c1a750c2164..d0a2cbb3e37 100644 --- a/docs/docs/assertions/datetime.md +++ b/docs/docs/assertions/datetime.md @@ -12,6 +12,7 @@ TUnit provides comprehensive assertions for date and time types, including `Date DateTime comparisons often need tolerance to account for timing variations: + ```csharp [Test] public async Task DateTime_With_Tolerance() @@ -29,6 +30,7 @@ public async Task DateTime_With_Tolerance() ### Tolerance Examples + ```csharp [Test] public async Task Various_Tolerance_Values() @@ -53,6 +55,7 @@ public async Task Various_Tolerance_Values() Standard comparison operators work with DateTime: + ```csharp [Test] public async Task DateTime_Comparison() @@ -71,6 +74,7 @@ public async Task DateTime_Comparison() ### IsToday / IsNotToday + ```csharp [Test] public async Task DateTime_Is_Today() @@ -88,6 +92,7 @@ public async Task DateTime_Is_Today() ### IsUtc / IsNotUtc + ```csharp [Test] public async Task DateTime_Kind() @@ -105,6 +110,7 @@ public async Task DateTime_Kind() ### IsLeapYear / IsNotLeapYear + ```csharp [Test] public async Task Leap_Year_Check() @@ -121,6 +127,7 @@ public async Task Leap_Year_Check() Compares against local time: + ```csharp [Test] public async Task Future_and_Past() @@ -137,6 +144,7 @@ public async Task Future_and_Past() Compares against UTC time: + ```csharp [Test] public async Task Future_and_Past_UTC() @@ -151,6 +159,7 @@ public async Task Future_and_Past_UTC() ### IsOnWeekend / IsOnWeekday + ```csharp [Test] public async Task Weekend_Check() @@ -166,6 +175,7 @@ public async Task Weekend_Check() ### IsDaylightSavingTime / IsNotDaylightSavingTime + ```csharp [Test] public async Task Daylight_Saving_Time() @@ -185,6 +195,7 @@ public async Task Daylight_Saving_Time() DateTimeOffset includes timezone information: + ```csharp [Test] public async Task DateTimeOffset_With_Tolerance() @@ -196,6 +207,7 @@ public async Task DateTimeOffset_With_Tolerance() } ``` + ```csharp [Test] public async Task DateTimeOffset_Comparison() @@ -212,6 +224,7 @@ public async Task DateTimeOffset_Comparison() DateOnly represents just a date without time: + ```csharp [Test] public async Task DateOnly_Assertions() @@ -225,6 +238,7 @@ public async Task DateOnly_Assertions() ### DateOnly with Days Tolerance + ```csharp [Test] public async Task DateOnly_With_Tolerance() @@ -238,6 +252,7 @@ public async Task DateOnly_With_Tolerance() ### DateOnly Comparison + ```csharp [Test] public async Task DateOnly_Comparison() @@ -254,6 +269,7 @@ public async Task DateOnly_Comparison() TimeOnly represents just time without a date: + ```csharp [Test] public async Task TimeOnly_Assertions() @@ -267,6 +283,7 @@ public async Task TimeOnly_Assertions() ### TimeOnly with Tolerance + ```csharp [Test] public async Task TimeOnly_With_Tolerance() @@ -282,6 +299,7 @@ public async Task TimeOnly_With_Tolerance() TimeSpan represents a duration: + ```csharp [Test] public async Task TimeSpan_Assertions() @@ -295,6 +313,7 @@ public async Task TimeSpan_Assertions() ### TimeSpan Comparison + ```csharp [Test] public async Task TimeSpan_Comparison() @@ -309,6 +328,7 @@ public async Task TimeSpan_Comparison() ### TimeSpan Sign Checks + ```csharp [Test] public async Task TimeSpan_Sign() @@ -325,6 +345,7 @@ public async Task TimeSpan_Sign() ### Expiration Checks + ```csharp [Test] public async Task Check_Token_Expiration() @@ -342,6 +363,7 @@ public async Task Check_Token_Expiration() ### Age Calculation + ```csharp [Test] public async Task Calculate_Age() @@ -361,6 +383,7 @@ public async Task Calculate_Age() ### Business Days + ```csharp [Test] public async Task Is_Business_Day() @@ -375,6 +398,7 @@ public async Task Is_Business_Day() ### Scheduling + ```csharp [Test] public async Task Scheduled_Time() @@ -389,6 +413,7 @@ public async Task Scheduled_Time() ### Performance Timing + ```csharp [Test] public async Task Operation_Duration() @@ -406,6 +431,7 @@ public async Task Operation_Duration() ### Date Range Validation + ```csharp [Test] public async Task Date_Within_Range() @@ -421,6 +447,7 @@ public async Task Date_Within_Range() ### Timestamp Validation + ```csharp [Test] public async Task Record_Created_Recently() @@ -437,6 +464,7 @@ public async Task Record_Created_Recently() ## Working with Date Components + ```csharp [Test] public async Task Date_Components() @@ -456,6 +484,7 @@ public async Task Date_Components() DayOfWeek has its own assertions: + ```csharp [Test] public async Task Day_Of_Week_Checks() @@ -475,6 +504,7 @@ public async Task Day_Of_Week_Checks() ## Chaining DateTime Assertions + ```csharp [Test] public async Task Chained_DateTime_Assertions() @@ -492,6 +522,7 @@ public async Task Chained_DateTime_Assertions() ### Birthday Validation + ```csharp [Test] public async Task Validate_Birthday() @@ -505,6 +536,7 @@ public async Task Validate_Birthday() ### Meeting Scheduler + ```csharp [Test] public async Task Schedule_Meeting() @@ -519,6 +551,7 @@ public async Task Schedule_Meeting() ### Relative Time Checks + ```csharp [Test] public async Task Within_Last_Hour() diff --git a/docs/docs/assertions/dictionaries.md b/docs/docs/assertions/dictionaries.md index 444b12c241c..9ee0ed982a4 100644 --- a/docs/docs/assertions/dictionaries.md +++ b/docs/docs/assertions/dictionaries.md @@ -14,6 +14,7 @@ TUnit provides specialized assertions for testing dictionaries (`IReadOnlyDictio Tests that a dictionary contains a specific key: + ```csharp [Test] public async Task Dictionary_Contains_Key() @@ -32,6 +33,7 @@ public async Task Dictionary_Contains_Key() #### With Custom Comparer + ```csharp [Test] public async Task Contains_Key_With_Comparer() @@ -52,6 +54,7 @@ public async Task Contains_Key_With_Comparer() Tests that a dictionary does not contain a specific key: + ```csharp [Test] public async Task Dictionary_Does_Not_Contain_Key() @@ -73,6 +76,7 @@ public async Task Dictionary_Does_Not_Contain_Key() Tests that a dictionary contains a specific value: + ```csharp [Test] public async Task Dictionary_Contains_Value() @@ -95,6 +99,7 @@ Dictionaries inherit all collection assertions since they implement `IEnumerable ### Count + ```csharp [Test] public async Task Dictionary_Count() @@ -112,6 +117,7 @@ public async Task Dictionary_Count() ### IsEmpty / IsNotEmpty + ```csharp [Test] public async Task Dictionary_Empty() @@ -126,6 +132,7 @@ public async Task Dictionary_Empty() ### Contains (KeyValuePair) + ```csharp [Test] public async Task Dictionary_Contains_Pair() @@ -142,6 +149,7 @@ public async Task Dictionary_Contains_Pair() ### All Pairs Match Condition + ```csharp [Test] public async Task All_Values_Positive() @@ -159,6 +167,7 @@ public async Task All_Values_Positive() ### Any Pair Matches Condition + ```csharp [Test] public async Task Any_Key_Starts_With() @@ -178,6 +187,7 @@ public async Task Any_Key_Starts_With() ### Configuration Validation + ```csharp [Test] public async Task Configuration_Has_Required_Keys() @@ -195,6 +205,7 @@ public async Task Configuration_Has_Required_Keys() ### HTTP Headers Validation + ```csharp [Test] public async Task Response_Headers() @@ -213,6 +224,7 @@ public async Task Response_Headers() ### Lookup Table Validation + ```csharp [Test] public async Task Lookup_Table() @@ -233,6 +245,7 @@ public async Task Lookup_Table() ### Cache Validation + ```csharp [Test] public async Task Cache_Contains_Entry() @@ -254,6 +267,7 @@ public async Task Cache_Contains_Entry() ### Accessing Values After Key Check + ```csharp [Test] public async Task Get_Value_After_Key_Check() @@ -274,6 +288,7 @@ public async Task Get_Value_After_Key_Check() ### TryGetValue Pattern + ```csharp [Test] public async Task TryGetValue_Pattern() @@ -294,6 +309,7 @@ public async Task TryGetValue_Pattern() ### Keys Collection + ```csharp [Test] public async Task Dictionary_Keys() @@ -317,6 +333,7 @@ public async Task Dictionary_Keys() ### Values Collection + ```csharp [Test] public async Task Dictionary_Values() @@ -342,6 +359,7 @@ public async Task Dictionary_Values() ### Same Key-Value Pairs + ```csharp [Test] public async Task Dictionaries_Are_Equivalent() @@ -365,6 +383,7 @@ public async Task Dictionaries_Are_Equivalent() ## Chaining Dictionary Assertions + ```csharp [Test] public async Task Chained_Dictionary_Assertions() @@ -390,6 +409,7 @@ public async Task Chained_Dictionary_Assertions() ### ConcurrentDictionary + ```csharp [Test] public async Task Concurrent_Dictionary() @@ -406,6 +426,7 @@ public async Task Concurrent_Dictionary() ### ReadOnlyDictionary + ```csharp [Test] public async Task ReadOnly_Dictionary() @@ -421,6 +442,7 @@ public async Task ReadOnly_Dictionary() ### SortedDictionary + ```csharp [Test] public async Task Sorted_Dictionary() @@ -442,6 +464,7 @@ public async Task Sorted_Dictionary() ### Null Dictionary + ```csharp [Test] public async Task Null_Dictionary() @@ -454,6 +477,7 @@ public async Task Null_Dictionary() ### Empty vs Null + ```csharp [Test] public async Task Empty_vs_Null_Dictionary() @@ -471,6 +495,7 @@ public async Task Empty_vs_Null_Dictionary() ### Required Configuration Keys + ```csharp [Test] public async Task All_Required_Keys_Present() @@ -487,6 +512,7 @@ public async Task All_Required_Keys_Present() Or with `Assert.Multiple`: + ```csharp [Test] public async Task All_Required_Keys_Present_Multiple() @@ -506,6 +532,7 @@ public async Task All_Required_Keys_Present_Multiple() ### Metadata Validation + ```csharp [Test] public async Task Validate_Metadata() @@ -522,6 +549,7 @@ public async Task Validate_Metadata() ### Feature Flags + ```csharp [Test] public async Task Feature_Flags() diff --git a/docs/docs/assertions/equality-and-comparison.md b/docs/docs/assertions/equality-and-comparison.md index 4b45d5ac524..9025e320700 100644 --- a/docs/docs/assertions/equality-and-comparison.md +++ b/docs/docs/assertions/equality-and-comparison.md @@ -14,6 +14,7 @@ TUnit provides comprehensive assertions for testing equality and comparing value Tests that two values are equal using the type's `Equals()` method or `==` operator: + ```csharp [Test] public async Task Basic_Equality() @@ -33,6 +34,7 @@ public async Task Basic_Equality() Tests that two values are not equal: + ```csharp [Test] public async Task Not_Equal() @@ -51,6 +53,7 @@ public async Task Not_Equal() Tests that two references point to the exact same object instance: + ```csharp [Test] public async Task Same_Reference() @@ -66,6 +69,7 @@ public async Task Same_Reference() Tests that two references point to different object instances: + ```csharp [Test] public async Task Different_References() @@ -85,6 +89,7 @@ All comparison assertions work with types that implement `IComparable` or `IC ### IsGreaterThan + ```csharp [Test] public async Task Greater_Than() @@ -102,6 +107,7 @@ public async Task Greater_Than() ### IsGreaterThanOrEqualTo + ```csharp [Test] public async Task Greater_Than_Or_Equal() @@ -116,6 +122,7 @@ public async Task Greater_Than_Or_Equal() ### IsLessThan + ```csharp [Test] public async Task Less_Than() @@ -130,6 +137,7 @@ public async Task Less_Than() ### IsLessThanOrEqualTo + ```csharp [Test] public async Task Less_Than_Or_Equal() @@ -146,6 +154,7 @@ public async Task Less_Than_Or_Equal() Tests that a value falls within a range (inclusive): + ```csharp [Test] public async Task Between_Values() @@ -163,6 +172,7 @@ public async Task Between_Values() Boundary values are included: + ```csharp [Test] public async Task Between_Includes_Boundaries() @@ -179,6 +189,7 @@ public async Task Between_Includes_Boundaries() Tests that a numeric value is greater than zero: + ```csharp [Test] public async Task Positive_Numbers() @@ -203,6 +214,7 @@ public async Task Positive_Numbers() Tests that a numeric value is less than zero: + ```csharp [Test] public async Task Negative_Numbers() @@ -221,6 +233,7 @@ When comparing floating-point numbers, you can specify a tolerance to account fo ### Double Tolerance + ```csharp [Test] public async Task Double_With_Tolerance() @@ -238,6 +251,7 @@ public async Task Double_With_Tolerance() ### Float Tolerance + ```csharp [Test] public async Task Float_With_Tolerance() @@ -251,6 +265,7 @@ public async Task Float_With_Tolerance() ### Decimal Tolerance + ```csharp [Test] public async Task Decimal_With_Tolerance() @@ -264,6 +279,7 @@ public async Task Decimal_With_Tolerance() ### Long Tolerance + ```csharp [Test] public async Task Long_With_Tolerance() @@ -281,6 +297,7 @@ public async Task Long_With_Tolerance() Combine multiple comparison assertions: + ```csharp [Test] public async Task Chained_Comparisons() @@ -296,6 +313,7 @@ public async Task Chained_Comparisons() Or use `IsBetween` for simpler range checks: + ```csharp [Test] public async Task Range_Check_Simplified() @@ -311,6 +329,7 @@ public async Task Range_Check_Simplified() You can provide custom equality comparers for collections and complex types: + ```csharp [Test] public async Task Custom_Comparer() @@ -338,6 +357,7 @@ public class PersonNameComparer : IEqualityComparer Or use a predicate: + ```csharp [Test] public async Task Custom_Equality_Predicate() @@ -356,6 +376,7 @@ public async Task Custom_Equality_Predicate() Equality works naturally with value types and records: + ```csharp public record Point(int X, int Y); @@ -371,6 +392,7 @@ public async Task Record_Equality() } ``` + ```csharp public struct Coordinate { diff --git a/docs/docs/assertions/exceptions.md b/docs/docs/assertions/exceptions.md index 413e3d7e01c..a1b86baa610 100644 --- a/docs/docs/assertions/exceptions.md +++ b/docs/docs/assertions/exceptions.md @@ -14,6 +14,7 @@ TUnit provides comprehensive assertions for testing that code throws (or doesn't Tests that a delegate throws a specific exception type (or a subclass): + ```csharp [Test] public async Task Code_Throws_Exception() @@ -25,6 +26,7 @@ public async Task Code_Throws_Exception() Works with any exception type: + ```csharp [Test] public async Task Various_Exception_Types() @@ -44,6 +46,7 @@ public async Task Various_Exception_Types() Tests that a delegate throws the exact exception type (not a subclass): + ```csharp [Test] public async Task Throws_Exact_Type() @@ -61,6 +64,7 @@ public async Task Throws_Exact_Type() Use when the exception type is only known at runtime. On a synchronous delegate, fluent chaining only supports the generic `Throws()` / `ThrowsExactly()` forms, so reach for the static `Assert.Throws(Type, Action)` helper instead. On an async delegate you can call `ThrowsAsync(Type)` directly. + ```csharp [Test] public async Task Throws_Runtime_Type_Sync() @@ -88,6 +92,7 @@ public async Task Throws_Runtime_Type_Async() Tests that code does not throw any exception: + ```csharp [Test] public async Task Code_Does_Not_Throw() @@ -104,6 +109,7 @@ public async Task Code_Does_Not_Throw() For async operations, use async delegates: + ```csharp [Test] public async Task Async_Throws_Exception() @@ -113,6 +119,7 @@ public async Task Async_Throws_Exception() } ``` + ```csharp [Test] public async Task Async_Does_Not_Throw() @@ -128,6 +135,7 @@ public async Task Async_Does_Not_Throw() Tests that the exception has an exact message: + ```csharp [Test] public async Task Exception_With_Exact_Message() @@ -142,6 +150,7 @@ public async Task Exception_With_Exact_Message() Tests that the exception message contains a substring: + ```csharp [Test] public async Task Exception_Message_Contains() @@ -154,6 +163,7 @@ public async Task Exception_Message_Contains() #### Case-Insensitive + ```csharp [Test] public async Task Message_Contains_Ignoring_Case() @@ -169,6 +179,7 @@ public async Task Message_Contains_Ignoring_Case() Tests that the exception message does not contain a substring: + ```csharp [Test] public async Task Message_Does_Not_Contain() @@ -183,6 +194,7 @@ public async Task Message_Does_Not_Contain() Tests that the exception message matches a pattern: + ```csharp [Test] public async Task Message_Matches_Pattern() @@ -195,6 +207,7 @@ public async Task Message_Matches_Pattern() Or with a `StringMatcher`: + ```csharp [Test] public async Task Message_Matches_With_Matcher() @@ -213,6 +226,7 @@ public async Task Message_Matches_With_Matcher() For `ArgumentException` and its subclasses, you can assert on the parameter name: + ```csharp [Test] public async Task ArgumentException_With_Parameter_Name() @@ -231,6 +245,7 @@ void ValidateUser(User user) Combine with message assertions: + ```csharp [Test] public async Task ArgumentException_Parameter_And_Message() @@ -254,6 +269,7 @@ void SetAge(int age) Assert on the inner exception: + ```csharp [Test] public async Task Exception_With_Inner_Exception() @@ -275,6 +291,7 @@ public async Task Exception_With_Inner_Exception() Chain to assert on the inner exception type: + ```csharp [Test] public async Task Inner_Exception_Type() @@ -302,6 +319,7 @@ void ThrowWithInner() ### Validation Exceptions + ```csharp [Test] public async Task Validate_Email_Throws() @@ -315,6 +333,7 @@ public async Task Validate_Email_Throws() ### Null Argument Checks + ```csharp [Test] public async Task Null_Argument_Throws() @@ -327,6 +346,7 @@ public async Task Null_Argument_Throws() ### File Operations + ```csharp [Test] public async Task File_Not_Found() @@ -339,6 +359,7 @@ public async Task File_Not_Found() ### Network Operations + ```csharp [Test] public async Task HTTP_Request_Fails() @@ -350,6 +371,7 @@ public async Task HTTP_Request_Fails() ### Database Operations + ```csharp [Test] public async Task Duplicate_Key_Violation() @@ -362,6 +384,7 @@ public async Task Duplicate_Key_Violation() ### Division by Zero + ```csharp [Test] public async Task Division_By_Zero() @@ -377,6 +400,7 @@ public async Task Division_By_Zero() ### Index Out of Range + ```csharp [Test] public async Task Array_Index_Out_Of_Range() @@ -390,6 +414,7 @@ public async Task Array_Index_Out_Of_Range() ### Invalid Cast + ```csharp [Test] public async Task Invalid_Cast() @@ -403,6 +428,7 @@ public async Task Invalid_Cast() ### Custom Exceptions + ```csharp public class BusinessRuleException : Exception { @@ -432,6 +458,7 @@ public async Task Custom_Exception_With_Properties() ### Using Assert.Multiple + ```csharp [Test] public async Task Multiple_Exception_Scenarios() @@ -454,6 +481,7 @@ public async Task Multiple_Exception_Scenarios() When using `Throws()`, subclasses are accepted: + ```csharp [Test] public async Task Exception_Inheritance() @@ -469,6 +497,7 @@ public async Task Exception_Inheritance() Use `ThrowsExactly()` if you need the exact type: + ```csharp [Test] public async Task Exact_Exception_Type() @@ -484,6 +513,7 @@ public async Task Exact_Exception_Type() ## Aggregate Exceptions + ```csharp [Test] public async Task Aggregate_Exception() @@ -499,6 +529,7 @@ public async Task Aggregate_Exception() ## Chaining Exception Assertions + ```csharp [Test] public async Task Chained_Exception_Assertions() @@ -515,6 +546,7 @@ public async Task Chained_Exception_Assertions() ### ThrowsNothing vs Try-Catch + ```csharp [Test] public async Task Explicit_No_Exception() @@ -532,6 +564,7 @@ public async Task Explicit_No_Exception() ### Expected Failures + ```csharp [Test] public async Task Expected_Validation_Failure() @@ -546,6 +579,7 @@ public async Task Expected_Validation_Failure() ### Defensive Programming + ```csharp [Test] public async Task Guard_Clause_Validation() @@ -558,6 +592,7 @@ public async Task Guard_Clause_Validation() ### State Validation + ```csharp [Test] public async Task Invalid_State_Operation() @@ -573,6 +608,7 @@ public async Task Invalid_State_Operation() ### Configuration Errors + ```csharp [Test] public async Task Missing_Configuration() @@ -585,6 +621,7 @@ public async Task Missing_Configuration() ## Timeout Exceptions + ```csharp [Test] public async Task Operation_Timeout() @@ -598,6 +635,7 @@ public async Task Operation_Timeout() ## Re-throwing Exceptions + ```csharp [Test] public async Task Wrapper_Exception() @@ -619,6 +657,7 @@ public async Task Wrapper_Exception() ## Exception Assertions with Async/Await + ```csharp [Test] public async Task Async_Exception_Handling() diff --git a/docs/docs/assertions/getting-started.md b/docs/docs/assertions/getting-started.md index 946e03597b2..05707d8fa94 100644 --- a/docs/docs/assertions/getting-started.md +++ b/docs/docs/assertions/getting-started.md @@ -12,6 +12,7 @@ TUnit provides a comprehensive, fluent assertion library that makes your tests r All assertions in TUnit follow a consistent pattern using the `Assert.That()` method: + ```csharp await Assert.That(actualValue).IsEqualTo(expectedValue); ``` @@ -25,6 +26,7 @@ The basic flow is: TUnit assertions must be awaited — they won't execute without `await`, and the test will pass silently: + ```csharp // ✅ Correct - awaited await Assert.That(result).IsEqualTo(42); @@ -43,6 +45,7 @@ TUnit provides assertions for all common scenarios: ### Equality & Comparison + ```csharp await Assert.That(actual).IsEqualTo(expected); await Assert.That(value).IsNotEqualTo(other); @@ -53,6 +56,7 @@ await Assert.That(temperature).IsBetween(20, 30); ### Strings + ```csharp await Assert.That(message).Contains("Hello"); await Assert.That(filename).StartsWith("test_"); @@ -62,6 +66,7 @@ await Assert.That(input).IsNotEmpty(); ### Collections + ```csharp await Assert.That(numbers).Contains(42); await Assert.That(items).Count().IsEqualTo(5); @@ -71,6 +76,7 @@ await Assert.That(values).All(x => x > 0); ### Booleans & Null + ```csharp await Assert.That(isValid).IsTrue(); await Assert.That(result).IsNotNull(); @@ -79,6 +85,7 @@ await Assert.That(optional).IsDefault(); ### Exceptions + ```csharp await Assert.That(() => DivideByZero()) .Throws() @@ -87,6 +94,7 @@ await Assert.That(() => DivideByZero()) ### Type Checking + ```csharp await Assert.That(obj).IsTypeOf(); await Assert.That(typeof(Dog)).IsAssignableTo(); @@ -96,6 +104,7 @@ await Assert.That(typeof(Dog)).IsAssignableTo(); Combine multiple assertions on the same value using `.And`: + ```csharp await Assert.That(username) .IsNotNull() @@ -106,6 +115,7 @@ await Assert.That(username) Use `.Or` when any condition can be true: + ```csharp await Assert.That(statusCode) .IsEqualTo(200) @@ -117,6 +127,7 @@ await Assert.That(statusCode) Group related assertions together so all failures are reported: + ```csharp using (Assert.Multiple()) { @@ -133,6 +144,7 @@ Instead of stopping at the first failure, `Assert.Multiple()` runs all assertion Assert on object properties using `.Member()`: + ```csharp await Assert.That(person) .Member(p => p.Name, name => name.IsEqualTo("Alice")) @@ -141,6 +153,7 @@ await Assert.That(person) This works with nested properties too: + ```csharp await Assert.That(order) .Member(o => o.Customer.Address.City, city => city.IsEqualTo("Seattle")); @@ -150,6 +163,7 @@ await Assert.That(order) Collections have rich assertion support: + ```csharp var numbers = new[] { 1, 2, 3, 4, 5 }; @@ -176,6 +190,7 @@ await Assert.That(numbers).IsEquivalentTo(new[] { 5, 4, 3, 2, 1 }); Some assertions return the value being tested, allowing you to continue working with it: + ```csharp // HasSingleItem returns the single item var user = await Assert.That(users).HasSingleItem(); @@ -190,12 +205,14 @@ await Assert.That(admin.Permissions).IsNotEmpty(); Use `.Satisfies()` for custom conditions: + ```csharp await Assert.That(value).Satisfies(v => v % 2 == 0, "Value must be even"); ``` Or map to a different value before asserting: + ```csharp await Assert.That(order) .Satisfies(o => o.Total, total => total > 100); @@ -205,6 +222,7 @@ await Assert.That(order) ### Testing Numeric Ranges + ```csharp await Assert.That(score).IsBetween(0, 100); await Assert.That(temperature).IsGreaterThanOrEqualTo(32); @@ -214,12 +232,14 @@ await Assert.That(temperature).IsGreaterThanOrEqualTo(32); For floating-point comparisons: + ```csharp await Assert.That(3.14159).IsEqualTo(Math.PI).Within(0.001); ``` ### Testing Async Operations + ```csharp await Assert.That(async () => await FetchDataAsync()) .Throws(); @@ -229,6 +249,7 @@ await Assert.That(longRunningTask).CompletesWithin(TimeSpan.FromSeconds(5)); ### Testing Multiple Conditions + ```csharp await Assert.That(username) .IsNotNull() @@ -240,6 +261,7 @@ await Assert.That(username) TUnit's assertions are strongly typed and catch type mismatches at compile time: + ```csharp int number = 42; string text = "42"; diff --git a/docs/docs/assertions/member-assertions.md b/docs/docs/assertions/member-assertions.md index cca3add44bf..507ec324a99 100644 --- a/docs/docs/assertions/member-assertions.md +++ b/docs/docs/assertions/member-assertions.md @@ -10,6 +10,7 @@ The `.Member()` method allows you to assert on object properties while maintaini ## Basic Usage + ```csharp [Test] public async Task BasicMemberAssertions() @@ -32,6 +33,7 @@ public async Task BasicMemberAssertions() The key advantage of `.Member()` is that it returns to the parent context after each assertion, allowing you to chain multiple property checks: + ```csharp [Test] public async Task MemberAssertionsWithFullContext() @@ -51,6 +53,7 @@ public async Task MemberAssertionsWithFullContext() Member assertions support nested properties: + ```csharp [Test] public async Task NestedPropertyAssertions() @@ -69,6 +72,7 @@ public async Task NestedPropertyAssertions() You can perform complex assertions on member values, including collections: + ```csharp [Test] public async Task ComplexMemberAssertions() @@ -90,6 +94,7 @@ public async Task ComplexMemberAssertions() Member assertions work with both `.And` and `.Or` combinators: + ```csharp [Test] public async Task MemberAssertionsWithOrLogic() @@ -111,6 +116,7 @@ public async Task MemberAssertionsWithOrLogic() ## Complete Example + ```csharp [Test] public async Task ComplexObjectValidation() @@ -128,6 +134,7 @@ public async Task ComplexObjectValidation() ## Nested Object Assertions + ```csharp [Test] public async Task NestedObjectAssertions() diff --git a/docs/docs/assertions/null-and-default.md b/docs/docs/assertions/null-and-default.md index 6617ebc8b59..0d72deea596 100644 --- a/docs/docs/assertions/null-and-default.md +++ b/docs/docs/assertions/null-and-default.md @@ -14,6 +14,7 @@ TUnit provides assertions for testing null values and default values. These asse Tests that a value is `null`: + ```csharp [Test] public async Task Null_Value() @@ -30,6 +31,7 @@ public async Task Null_Value() Tests that a value is not `null`: + ```csharp [Test] public async Task Not_Null_Value() @@ -46,6 +48,7 @@ public async Task Not_Null_Value() When you use `IsNotNull()`, C#'s nullability analysis understands that the value is non-null afterward: + ```csharp [Test] public async Task Nullability_Flow() @@ -62,6 +65,7 @@ public async Task Nullability_Flow() This works with chaining too: + ```csharp [Test] public async Task Chained_After_Null_Check() @@ -81,6 +85,7 @@ public async Task Chained_After_Null_Check() Tests that a value equals the default value for its type: + ```csharp [Test] public async Task Default_Values() @@ -108,6 +113,7 @@ public async Task Default_Values() Tests that a value is not the default value for its type: + ```csharp [Test] public async Task Not_Default_Values() @@ -132,6 +138,7 @@ public async Task Not_Default_Values() For reference types, default equals `null`: + ```csharp [Test] public async Task Reference_Type_Defaults() @@ -150,6 +157,7 @@ public async Task Reference_Type_Defaults() For value types, default is the zero-initialized value: + ```csharp [Test] public async Task Value_Type_Defaults() @@ -179,6 +187,7 @@ public async Task Value_Type_Defaults() Nullable value types (`T?`) are reference types, so their default is `null`: + ```csharp [Test] public async Task Nullable_Value_Type_Defaults() @@ -197,6 +206,7 @@ public async Task Nullable_Value_Type_Defaults() ### Optional Parameters and Returns + ```csharp [Test] public async Task Optional_Return_Value() @@ -213,6 +223,7 @@ public async Task Optional_Return_Value() ### Initialization Checks + ```csharp [Test] public async Task Uninitialized_Field() @@ -231,6 +242,7 @@ public async Task Uninitialized_Field() ### Dependency Injection Validation + ```csharp [Test] public async Task Constructor_Injection() @@ -245,6 +257,7 @@ public async Task Constructor_Injection() ### Lazy Initialization + ```csharp [Test] public async Task Lazy_Property() @@ -265,6 +278,7 @@ public async Task Lazy_Property() Use `Assert.Multiple()` to check multiple null conditions: + ```csharp [Test] public async Task Validate_All_Required_Fields() @@ -284,6 +298,7 @@ public async Task Validate_All_Required_Fields() Or chain them: + ```csharp [Test] public async Task Required_Fields_With_Chaining() @@ -301,6 +316,7 @@ public async Task Required_Fields_With_Chaining() ### Structs + ```csharp public struct Rectangle { @@ -321,6 +337,7 @@ public async Task Struct_Default() ### Records + ```csharp public record Person(string Name, int Age); @@ -348,6 +365,7 @@ public async Task Record_Struct_Default() ### Empty Collections vs Null + ```csharp [Test] public async Task Empty_vs_Null() @@ -363,6 +381,7 @@ public async Task Empty_vs_Null() ### Empty Strings vs Null + ```csharp [Test] public async Task Empty_String_vs_Null() @@ -378,6 +397,7 @@ public async Task Empty_String_vs_Null() ### Default GUID + ```csharp [Test] public async Task GUID_Default() @@ -392,6 +412,7 @@ public async Task GUID_Default() ### Default DateTime + ```csharp [Test] public async Task DateTime_Default() @@ -407,6 +428,7 @@ public async Task DateTime_Default() ### Validate Required Dependencies + ```csharp [Test] public async Task All_Dependencies_Provided() @@ -421,6 +443,7 @@ public async Task All_Dependencies_Provided() ### Validate Optional Features + ```csharp [Test] public async Task Optional_Feature_Not_Enabled() @@ -436,6 +459,7 @@ public async Task Optional_Feature_Not_Enabled() ### State Machine Validation + ```csharp [Test] public async Task State_Transitions() diff --git a/docs/docs/assertions/numeric.md b/docs/docs/assertions/numeric.md index cdf2292c95c..42fbdc30c63 100644 --- a/docs/docs/assertions/numeric.md +++ b/docs/docs/assertions/numeric.md @@ -14,6 +14,7 @@ TUnit provides comprehensive assertions for testing numeric values, including sp Tests that a numeric value is greater than zero: + ```csharp [Test] public async Task Positive_Values() @@ -31,6 +32,7 @@ public async Task Positive_Values() Works with all numeric types: + ```csharp [Test] public async Task All_Numeric_Types() @@ -52,6 +54,7 @@ public async Task All_Numeric_Types() Tests that a numeric value is less than zero: + ```csharp [Test] public async Task Negative_Values() @@ -69,6 +72,7 @@ public async Task Negative_Values() ### Zero is Neither Positive Nor Negative + ```csharp [Test] public async Task Zero_Checks() @@ -90,6 +94,7 @@ All comparison operators work with numeric types. See [Equality and Comparison]( ### Quick Reference + ```csharp [Test] public async Task Numeric_Comparisons() @@ -110,6 +115,7 @@ Floating-point arithmetic can introduce rounding errors. Use tolerance for safe ### Double Tolerance + ```csharp [Test] public async Task Double_Tolerance() @@ -127,6 +133,7 @@ public async Task Double_Tolerance() ### Float Tolerance + ```csharp [Test] public async Task Float_Tolerance() @@ -142,6 +149,7 @@ public async Task Float_Tolerance() Useful for monetary calculations: + ```csharp [Test] public async Task Decimal_Tolerance() @@ -157,6 +165,7 @@ public async Task Decimal_Tolerance() For timestamp or large number comparisons: + ```csharp [Test] public async Task Long_Tolerance() @@ -174,6 +183,7 @@ public async Task Long_Tolerance() ### Financial Calculations + ```csharp [Test] public async Task Calculate_Total_Price() @@ -193,6 +203,7 @@ public async Task Calculate_Total_Price() ### Temperature Conversions + ```csharp [Test] public async Task Celsius_To_Fahrenheit() @@ -207,6 +218,7 @@ public async Task Celsius_To_Fahrenheit() ### Percentage Calculations + ```csharp [Test] public async Task Calculate_Percentage() @@ -223,6 +235,7 @@ public async Task Calculate_Percentage() ### Statistical Calculations + ```csharp [Test] public async Task Calculate_Average() @@ -240,6 +253,7 @@ public async Task Calculate_Average() ### Valid Range Checks + ```csharp [Test] public async Task Validate_Age() @@ -253,6 +267,7 @@ public async Task Validate_Age() ### Percentage Range + ```csharp [Test] public async Task Validate_Percentage() @@ -266,6 +281,7 @@ public async Task Validate_Percentage() ### Score Validation + ```csharp [Test] public async Task Validate_Score() @@ -281,6 +297,7 @@ public async Task Validate_Score() ## Chaining Numeric Assertions + ```csharp [Test] public async Task Chained_Numeric_Assertions() @@ -297,6 +314,7 @@ public async Task Chained_Numeric_Assertions() ## Nullable Numeric Types + ```csharp [Test] public async Task Nullable_Numerics() @@ -321,6 +339,7 @@ public async Task Nullable_Null() ### Infinity + ```csharp [Test] public async Task Infinity_Checks() @@ -335,6 +354,7 @@ public async Task Infinity_Checks() ### NaN (Not a Number) + ```csharp [Test] public async Task NaN_Checks() @@ -351,6 +371,7 @@ public async Task NaN_Checks() ## Performance Metrics + ```csharp [Test] public async Task Response_Time_Check() @@ -370,6 +391,7 @@ public async Task Response_Time_Check() ### Boundary Testing + ```csharp [Test] public async Task Boundary_Values() @@ -385,6 +407,7 @@ public async Task Boundary_Values() ### Growth Rate Validation + ```csharp [Test] public async Task Growth_Rate() @@ -400,6 +423,7 @@ public async Task Growth_Rate() ### Ratio Calculations + ```csharp [Test] public async Task Success_Ratio() diff --git a/docs/docs/assertions/regex-assertions.md b/docs/docs/assertions/regex-assertions.md index bbc8f9a70d1..b834d5c1ac2 100644 --- a/docs/docs/assertions/regex-assertions.md +++ b/docs/docs/assertions/regex-assertions.md @@ -40,6 +40,7 @@ The key advantage of regex assertions is the ability to assert on capture groups ### Named Groups + ```csharp [Test] public async Task NamedGroupAssertions() @@ -57,6 +58,7 @@ public async Task NamedGroupAssertions() ### Indexed Groups + ```csharp [Test] public async Task IndexedGroupAssertions() @@ -78,6 +80,7 @@ public async Task IndexedGroupAssertions() When a regex matches multiple times in a string, you can access specific matches using `.Match(index)`: + ```csharp [Test] public async Task MultipleMatchAssertions() @@ -102,6 +105,7 @@ public async Task MultipleMatchAssertions() To assert on where a match occurs or how long it is, use `.Match(index)` to select a match from the collection, then assert on the resulting `RegexMatch` (you can also combine this with `Regex.Match(...)` directly if you need more detailed inspection): + ```csharp [Test] public async Task PositionAndLengthAssertions() @@ -124,6 +128,7 @@ public async Task PositionAndLengthAssertions() ## Complex Patterns with Multiple Groups + ```csharp [Test] public async Task ComplexPatternAssertions() @@ -142,6 +147,7 @@ public async Task ComplexPatternAssertions() ## Product Information Validation + ```csharp [Test] public async Task ProductCodeValidation() @@ -159,6 +165,7 @@ public async Task ProductCodeValidation() ## URL Parsing + ```csharp [Test] public async Task UrlParsingAssertions() @@ -180,6 +187,7 @@ public async Task UrlParsingAssertions() The `Matches(string)` overload does not take `RegexOptions`. To apply options like case-insensitivity, construct a `Regex` (or use a source-generated regex) with the desired options and pass it to `Matches`: + ```csharp [Test] public async Task RegexOptionsAssertions() @@ -225,6 +233,7 @@ public partial class MyTests Handle optional capture groups that may be empty: + ```csharp [Test] public async Task OptionalGroupAssertions() @@ -249,6 +258,7 @@ public async Task OptionalGroupAssertions() ## Complete Example + ```csharp [Test] public async Task CompleteEmailValidation() @@ -274,6 +284,7 @@ public async Task CompleteEmailValidation() The regex assertions surface standard exceptions for common error cases. Wrap the call in an `Assert.That(() => ...)` delegate and assert on the thrown exception type: + ```csharp [Test] public async Task RegexAssertionErrors() diff --git a/docs/docs/assertions/specialized-types.md b/docs/docs/assertions/specialized-types.md index ac9bc051eca..097eb7353b4 100644 --- a/docs/docs/assertions/specialized-types.md +++ b/docs/docs/assertions/specialized-types.md @@ -14,6 +14,7 @@ TUnit provides assertions for many specialized .NET types beyond the common prim Tests whether a GUID is empty (`Guid.Empty`): + ```csharp [Test] public async Task GUID_Is_Empty() @@ -28,6 +29,7 @@ public async Task GUID_Is_Empty() Practical usage: + ```csharp [Test] public async Task Entity_Has_Valid_ID() @@ -45,6 +47,7 @@ public async Task Entity_Has_Valid_ID() Tests for 2xx success status codes: + ```csharp [Test] public async Task HTTP_Success_Status() @@ -57,6 +60,7 @@ public async Task HTTP_Success_Status() Works with all 2xx codes: + ```csharp [Test] public async Task Various_Success_Codes() @@ -70,6 +74,7 @@ public async Task Various_Success_Codes() ### IsNotSuccess + ```csharp [Test] public async Task HTTP_Not_Success() @@ -83,6 +88,7 @@ public async Task HTTP_Not_Success() Tests for 4xx client error status codes: + ```csharp [Test] public async Task HTTP_Client_Error() @@ -98,6 +104,7 @@ public async Task HTTP_Client_Error() Tests for 5xx server error status codes: + ```csharp [Test] public async Task HTTP_Server_Error() @@ -112,6 +119,7 @@ public async Task HTTP_Server_Error() Tests for 3xx redirection status codes: + ```csharp [Test] public async Task HTTP_Redirection() @@ -126,6 +134,7 @@ public async Task HTTP_Redirection() ### IsCancellationRequested / IsNotCancellationRequested + ```csharp [Test] public async Task CancellationToken_Is_Requested() @@ -147,6 +156,7 @@ public async Task CancellationToken_Not_Requested() ### CanBeCanceled / CannotBeCanceled + ```csharp [Test] public async Task Token_Can_Be_Canceled() @@ -169,6 +179,7 @@ public async Task Default_Token_Cannot_Be_Canceled() ### IsLetter / IsNotLetter + ```csharp [Test] public async Task Char_Is_Letter() @@ -183,6 +194,7 @@ public async Task Char_Is_Letter() ### IsDigit / IsNotDigit + ```csharp [Test] public async Task Char_Is_Digit() @@ -196,6 +208,7 @@ public async Task Char_Is_Digit() ### IsWhiteSpace / IsNotWhiteSpace + ```csharp [Test] public async Task Char_Is_WhiteSpace() @@ -210,6 +223,7 @@ public async Task Char_Is_WhiteSpace() ### IsUpper / IsNotUpper + ```csharp [Test] public async Task Char_Is_Upper() @@ -223,6 +237,7 @@ public async Task Char_Is_Upper() ### IsLower / IsNotLower + ```csharp [Test] public async Task Char_Is_Lower() @@ -236,6 +251,7 @@ public async Task Char_Is_Lower() ### IsPunctuation / IsNotPunctuation + ```csharp [Test] public async Task Char_Is_Punctuation() @@ -254,6 +270,7 @@ public async Task Char_Is_Punctuation() #### Exists / DoesNotExist + ```csharp [Test] public async Task Directory_Exists() @@ -274,6 +291,7 @@ public async Task Directory_Does_Not_Exist() #### HasFiles / IsEmpty + ```csharp [Test] public async Task Directory_Has_Files() @@ -298,6 +316,7 @@ public async Task Directory_Is_Empty() #### HasSubdirectories / HasNoSubdirectories + ```csharp [Test] public async Task Directory_Has_Subdirectories() @@ -312,6 +331,7 @@ public async Task Directory_Has_Subdirectories() #### Exists / DoesNotExist + ```csharp [Test] public async Task File_Exists() @@ -336,6 +356,7 @@ public async Task File_Does_Not_Exist() #### IsReadOnly / IsNotReadOnly + ```csharp [Test] public async Task File_Is_ReadOnly() @@ -356,6 +377,7 @@ public async Task File_Is_ReadOnly() #### IsHidden / IsNotHidden + ```csharp [Test] public async Task File_Is_Hidden() @@ -374,6 +396,7 @@ public async Task File_Is_Hidden() #### IsSystem / IsNotSystem + ```csharp [Test] public async Task File_Is_System() @@ -390,6 +413,7 @@ public async Task File_Is_System() #### IsExecutable / IsNotExecutable + ```csharp [Test] public async Task File_Is_Executable() @@ -407,6 +431,7 @@ public async Task File_Is_Executable() ### IsIPv4 / IsNotIPv4 + ```csharp [Test] public async Task IP_Is_IPv4() @@ -427,6 +452,7 @@ public async Task IP_Not_IPv4() ### IsIPv6 / IsNotIPv6 + ```csharp [Test] public async Task IP_Is_IPv6() @@ -449,6 +475,7 @@ public async Task IP_Not_IPv6() ### IsValueCreated / IsNotValueCreated + ```csharp [Test] public async Task Lazy_Value_Not_Created() @@ -468,6 +495,7 @@ public async Task Lazy_Value_Not_Created() ### CanRead / CannotRead + ```csharp [Test] public async Task Stream_Can_Read() @@ -480,6 +508,7 @@ public async Task Stream_Can_Read() ### CanWrite / CannotWrite + ```csharp [Test] public async Task Stream_Can_Write() @@ -500,6 +529,7 @@ public async Task Stream_Cannot_Write() ### CanSeek / CannotSeek + ```csharp [Test] public async Task Stream_Can_Seek() @@ -512,6 +542,7 @@ public async Task Stream_Can_Seek() ### CanTimeout / CannotTimeout + ```csharp [Test] public async Task Network_Stream_Can_Timeout() @@ -526,6 +557,7 @@ public async Task Network_Stream_Can_Timeout() ### HasExited / HasNotExited + ```csharp [Test] public async Task Process_Has_Not_Exited() @@ -543,6 +575,7 @@ public async Task Process_Has_Not_Exited() ### IsResponding / IsNotResponding + ```csharp [Test] public async Task Process_Is_Responding() @@ -557,6 +590,7 @@ public async Task Process_Is_Responding() ### IsAlive / IsNotAlive + ```csharp [Test] public async Task Thread_Is_Alive() @@ -573,6 +607,7 @@ public async Task Thread_Is_Alive() ### IsBackground / IsNotBackground + ```csharp [Test] public async Task Thread_Is_Background() @@ -586,6 +621,7 @@ public async Task Thread_Is_Background() ### IsThreadPoolThread / IsNotThreadPoolThread + ```csharp [Test] public async Task Check_ThreadPool_Thread() @@ -601,6 +637,7 @@ public async Task Check_ThreadPool_Thread() ### IsAlive / IsNotAlive + ```csharp [Test] public async Task WeakReference_Is_Alive() @@ -622,6 +659,7 @@ public async Task WeakReference_Is_Alive() ### IsAbsoluteUri / IsNotAbsoluteUri + ```csharp [Test] public async Task URI_Is_Absolute() @@ -644,6 +682,7 @@ public async Task URI_Is_Relative() ### IsUtf8 / IsNotUtf8 + ```csharp [Test] public async Task Encoding_Is_UTF8() @@ -666,6 +705,7 @@ public async Task Encoding_Not_UTF8() Version comparisons using standard comparison operators: + ```csharp [Test] public async Task Version_Comparison() @@ -682,6 +722,7 @@ public async Task Version_Comparison() ### IsWeekend / IsNotWeekend + ```csharp [Test] public async Task Day_Is_Weekend() @@ -693,6 +734,7 @@ public async Task Day_Is_Weekend() ### IsWeekday / IsNotWeekday + ```csharp [Test] public async Task Day_Is_Weekday() @@ -709,6 +751,7 @@ public async Task Day_Is_Weekday() ### API Testing + ```csharp [Test] public async Task API_Returns_Success() @@ -722,6 +765,7 @@ public async Task API_Returns_Success() ### File Upload Validation + ```csharp [Test] public async Task Uploaded_File_Validation() @@ -736,6 +780,7 @@ public async Task Uploaded_File_Validation() ### Configuration Directory Check + ```csharp [Test] public async Task Config_Directory_Setup() @@ -749,6 +794,7 @@ public async Task Config_Directory_Setup() ### Network Validation + ```csharp [Test] public async Task Server_IP_Is_Valid() diff --git a/docs/docs/assertions/string.md b/docs/docs/assertions/string.md index 0844ab43742..e67c4263056 100644 --- a/docs/docs/assertions/string.md +++ b/docs/docs/assertions/string.md @@ -14,6 +14,7 @@ TUnit provides rich assertions for testing strings, including substring matching Tests that a string contains a substring: + ```csharp [Test] public async Task String_Contains() @@ -28,6 +29,7 @@ public async Task String_Contains() #### Case-Insensitive Contains + ```csharp [Test] public async Task Contains_Ignoring_Case() @@ -46,6 +48,7 @@ public async Task Contains_Ignoring_Case() #### With String Comparison + ```csharp [Test] public async Task Contains_With_Comparison() @@ -60,6 +63,7 @@ public async Task Contains_With_Comparison() #### With Trimming + ```csharp [Test] public async Task Contains_With_Trimming() @@ -74,6 +78,7 @@ public async Task Contains_With_Trimming() #### Ignoring Whitespace + ```csharp [Test] public async Task Contains_Ignoring_Whitespace() @@ -90,6 +95,7 @@ public async Task Contains_Ignoring_Whitespace() Tests that a string does not contain a substring: + ```csharp [Test] public async Task String_Does_Not_Contain() @@ -103,6 +109,7 @@ public async Task String_Does_Not_Contain() All modifiers work with `DoesNotContain`: + ```csharp [Test] public async Task Does_Not_Contain_Ignoring_Case() @@ -119,6 +126,7 @@ public async Task Does_Not_Contain_Ignoring_Case() Tests that a string starts with a specific prefix: + ```csharp [Test] public async Task String_Starts_With() @@ -134,6 +142,7 @@ public async Task String_Starts_With() With case-insensitive comparison: + ```csharp [Test] public async Task Starts_With_Ignoring_Case() @@ -150,6 +159,7 @@ public async Task Starts_With_Ignoring_Case() Tests that a string ends with a specific suffix: + ```csharp [Test] public async Task String_Ends_With() @@ -165,6 +175,7 @@ public async Task String_Ends_With() With case-insensitive comparison: + ```csharp [Test] public async Task Ends_With_Ignoring_Case() @@ -183,6 +194,7 @@ public async Task Ends_With_Ignoring_Case() Tests that a string matches a regular expression pattern: + ```csharp [Test] public async Task String_Matches_Pattern() @@ -195,6 +207,7 @@ public async Task String_Matches_Pattern() With a compiled `Regex`: + ```csharp [Test] public async Task Matches_With_Regex() @@ -208,6 +221,7 @@ public async Task Matches_With_Regex() #### Case-Insensitive Matching + ```csharp [Test] public async Task Matches_Ignoring_Case() @@ -222,6 +236,7 @@ public async Task Matches_Ignoring_Case() #### With Regex Options + ```csharp [Test] public async Task Matches_With_Options() @@ -238,6 +253,7 @@ public async Task Matches_With_Options() Tests that a string does not match a pattern: + ```csharp [Test] public async Task String_Does_Not_Match() @@ -254,6 +270,7 @@ public async Task String_Does_Not_Match() Tests that a string is empty (`""`): + ```csharp [Test] public async Task String_Is_Empty() @@ -266,6 +283,7 @@ public async Task String_Is_Empty() Note: This checks for an empty string, not `null`: + ```csharp [Test] public async Task Empty_vs_Null() @@ -283,6 +301,7 @@ public async Task Empty_vs_Null() Tests that a string is not empty: + ```csharp [Test] public async Task String_Is_Not_Empty() @@ -297,6 +316,7 @@ public async Task String_Is_Not_Empty() Tests that a string has a specific length: + ```csharp [Test] public async Task String_Has_Length() @@ -309,6 +329,7 @@ public async Task String_Has_Length() With chained comparison: + ```csharp [Test] public async Task Length_With_Comparison() @@ -323,6 +344,7 @@ public async Task Length_With_Comparison() Using `IsBetween`: + ```csharp [Test] public async Task Length_Range() @@ -339,6 +361,7 @@ public async Task Length_Range() String equality with various comparison options: + ```csharp [Test] public async Task String_Equality() @@ -352,6 +375,7 @@ public async Task String_Equality() #### Ignoring Case + ```csharp [Test] public async Task Equality_Ignoring_Case() @@ -367,6 +391,7 @@ public async Task Equality_Ignoring_Case() #### With String Comparison + ```csharp [Test] public async Task Equality_With_Comparison() @@ -384,6 +409,7 @@ public async Task Equality_With_Comparison() You can parse strings to other types and assert on the result: + ```csharp [Test] public async Task Parse_String_To_Int() @@ -395,6 +421,7 @@ public async Task Parse_String_To_Int() } ``` + ```csharp [Test] public async Task Parse_String_To_DateTime() @@ -410,6 +437,7 @@ public async Task Parse_String_To_DateTime() ### Email Validation + ```csharp [Test] public async Task Validate_Email() @@ -425,6 +453,7 @@ public async Task Validate_Email() ### URL Validation + ```csharp [Test] public async Task Validate_URL() @@ -440,6 +469,7 @@ public async Task Validate_URL() ### File Extension Check + ```csharp [Test] public async Task Check_File_Extension() @@ -454,6 +484,7 @@ public async Task Check_File_Extension() ### Username Validation + ```csharp [Test] public async Task Validate_Username() @@ -470,6 +501,7 @@ public async Task Validate_Username() ### Password Requirements + ```csharp [Test] public async Task Validate_Password() @@ -487,6 +519,7 @@ public async Task Validate_Password() ### JSON String Content + ```csharp [Test] public async Task Check_JSON_Content() @@ -503,6 +536,7 @@ public async Task Check_JSON_Content() ### SQL Query Validation + ```csharp [Test] public async Task Validate_SQL_Query() @@ -520,6 +554,7 @@ public async Task Validate_SQL_Query() ### IsNullOrEmpty Equivalent + ```csharp [Test] public async Task Check_Null_Or_Empty() @@ -541,6 +576,7 @@ public async Task Check_Null_Or_Empty() ### IsNullOrWhiteSpace Equivalent + ```csharp [Test] public async Task Check_Null_Or_Whitespace() @@ -553,6 +589,7 @@ public async Task Check_Null_Or_Whitespace() Better with trimming: + ```csharp [Test] public async Task Require_Non_Whitespace() @@ -572,6 +609,7 @@ public async Task Require_Non_Whitespace() TUnit also supports assertions on `StringBuilder`: + ```csharp [Test] public async Task StringBuilder_Tests() @@ -590,6 +628,7 @@ public async Task StringBuilder_Tests() ## Chaining String Assertions + ```csharp [Test] public async Task Chained_String_Assertions() @@ -608,6 +647,7 @@ public async Task Chained_String_Assertions() ## Case Sensitivity Patterns + ```csharp [Test] public async Task Case_Sensitivity() @@ -631,6 +671,7 @@ public async Task Case_Sensitivity() ## String Formatting Validation + ```csharp [Test] public async Task Formatted_String() @@ -648,6 +689,7 @@ public async Task Formatted_String() ## Multi-line Strings + ```csharp [Test] public async Task Multiline_String() @@ -667,6 +709,7 @@ public async Task Multiline_String() ## Common String Comparison Options + ```csharp [Test] public async Task String_Comparison_Options() @@ -692,6 +735,7 @@ public async Task String_Comparison_Options() ## Path Validation + ```csharp [Test] public async Task File_Path_Validation() @@ -707,6 +751,7 @@ public async Task File_Path_Validation() Unix path: + ```csharp [Test] public async Task Unix_Path_Validation() @@ -724,6 +769,7 @@ public async Task Unix_Path_Validation() ### Trim and Assert + ```csharp [Test] public async Task Trim_Before_Assert() @@ -737,6 +783,7 @@ public async Task Trim_Before_Assert() ### Case Normalization + ```csharp [Test] public async Task Normalize_Case() @@ -750,6 +797,7 @@ public async Task Normalize_Case() ### Substring Extraction + ```csharp [Test] public async Task Extract_Substring() diff --git a/docs/docs/assertions/tasks-and-async.md b/docs/docs/assertions/tasks-and-async.md index 3a7bd6f6536..04d34be5cec 100644 --- a/docs/docs/assertions/tasks-and-async.md +++ b/docs/docs/assertions/tasks-and-async.md @@ -14,6 +14,7 @@ TUnit provides specialized assertions for testing `Task` and `Task` objects, Tests whether a task has completed (successfully, faulted, or canceled): + ```csharp [Test] public async Task Task_Is_Completed() @@ -30,6 +31,7 @@ public async Task Task_Is_Completed() Tests whether a task was canceled: + ```csharp [Test] public async Task Task_Is_Canceled() @@ -52,6 +54,7 @@ public async Task Task_Is_Canceled() } ``` + ```csharp [Test] public async Task Task_Not_Canceled() @@ -66,6 +69,7 @@ public async Task Task_Not_Canceled() Tests whether a task ended in a faulted state (threw an exception): + ```csharp [Test] public async Task Task_Is_Faulted() @@ -85,6 +89,7 @@ public async Task Task_Is_Faulted() } ``` + ```csharp [Test] public async Task Task_Not_Faulted() @@ -99,6 +104,7 @@ public async Task Task_Not_Faulted() Tests whether a task completed successfully (not faulted or canceled): + ```csharp [Test] public async Task Task_Completed_Successfully() @@ -109,6 +115,7 @@ public async Task Task_Completed_Successfully() } ``` + ```csharp [Test] public async Task Task_Not_Completed_Successfully() @@ -127,6 +134,7 @@ public async Task Task_Not_Completed_Successfully() Tests that a task completes within a specified time: + ```csharp [Test] public async Task Task_Completes_Within_Timeout() @@ -139,6 +147,7 @@ public async Task Task_Completes_Within_Timeout() Fails if timeout exceeded: + ```csharp [Test] public async Task Task_Exceeds_Timeout() @@ -154,6 +163,7 @@ public async Task Task_Exceeds_Timeout() Polls a value source until a nested assertion passes or the timeout expires. `WaitsFor` takes an assertion-builder lambda (not a bool predicate), so you write the same fluent assertions you would elsewhere: + ```csharp [Test] public async Task Wait_For_Condition() @@ -177,6 +187,7 @@ public async Task Wait_For_Condition() ### API Call Timeout + ```csharp [Test] public async Task API_Call_Completes_In_Time() @@ -192,6 +203,7 @@ public async Task API_Call_Completes_In_Time() ### Background Task Completion + ```csharp [Test] public async Task Background_Processing_Completes() @@ -205,6 +217,7 @@ public async Task Background_Processing_Completes() ### Cancellation Token Handling + ```csharp [Test] public async Task Operation_Respects_Cancellation() @@ -231,6 +244,7 @@ public async Task Operation_Respects_Cancellation() For testing exceptions in async code, use exception assertions: + ```csharp [Test] public async Task Async_Method_Throws_Exception() @@ -244,6 +258,7 @@ public async Task Async_Method_Throws_Exception() For `Task`, await the task first, then assert on the result: + ```csharp [Test] public async Task Task_Returns_Expected_Result() @@ -263,6 +278,7 @@ public async Task Task_Returns_Expected_Result() ### Parallel Task Execution + ```csharp [Test] public async Task Parallel_Tasks_Complete() @@ -280,6 +296,7 @@ public async Task Parallel_Tasks_Complete() ### Task State Transitions + ```csharp [Test] public async Task Task_State_Progression() @@ -304,6 +321,7 @@ public async Task Task_State_Progression() ### Failed Task + ```csharp [Test] public async Task Task_Fails_With_Exception() @@ -320,6 +338,7 @@ public async Task Task_Fails_With_Exception() ### Canceled Task + ```csharp [Test] public async Task Task_Can_Be_Canceled() @@ -338,6 +357,7 @@ public async Task Task_Can_Be_Canceled() ### WhenAll Completion + ```csharp [Test] public async Task All_Tasks_Complete() @@ -354,6 +374,7 @@ public async Task All_Tasks_Complete() ### WhenAny Completion + ```csharp [Test] public async Task Any_Task_Completes() @@ -374,6 +395,7 @@ public async Task Any_Task_Completes() `ValueTask` and `ValueTask` work similarly: + ```csharp [Test] public async Task ValueTask_Completion() @@ -393,6 +415,7 @@ async ValueTask GetValueTaskAsync() ## Chaining Task Assertions + ```csharp [Test] public async Task Chained_Task_Assertions() @@ -414,6 +437,7 @@ public async Task Chained_Task_Assertions() ### Retry Logic Testing + ```csharp [Test] public async Task Retry_Eventually_Succeeds() @@ -436,6 +460,7 @@ public async Task Retry_Eventually_Succeeds() ### Debounce Testing + ```csharp [Test] public async Task Debounced_Operation() @@ -455,6 +480,7 @@ public async Task Debounced_Operation() ### Circuit Breaker Testing + ```csharp [Test] public async Task Circuit_Breaker_Opens() @@ -481,6 +507,7 @@ public async Task Circuit_Breaker_Opens() ### Producer-Consumer Testing + ```csharp [Test] public async Task Producer_Consumer_Processes_Items() @@ -497,6 +524,7 @@ public async Task Producer_Consumer_Processes_Items() ### Rate Limiting + ```csharp [Test] public async Task Rate_Limiter_Delays_Requests() @@ -518,6 +546,7 @@ public async Task Rate_Limiter_Delays_Requests() ## Testing Async Disposal + ```csharp [Test] public async Task Async_Disposable_Cleanup() diff --git a/docs/docs/assertions/type-checking.md b/docs/docs/assertions/type-checking.md index d47f64e4932..d908b104b0f 100644 --- a/docs/docs/assertions/type-checking.md +++ b/docs/docs/assertions/type-checking.md @@ -10,6 +10,7 @@ TUnit assertions check types at compile time wherever possible. This gives faste For example, this wouldn't compile because we're comparing an `int` and a `string`: + ```csharp [Test] public async Task MyTest() @@ -26,6 +27,7 @@ When you need to verify types at runtime — for example, when working with poly Tests that a value is exactly the specified type (not a subclass): + ```csharp [Test] public async Task Exact_Type() @@ -40,6 +42,7 @@ public async Task Exact_Type() Tests that a value can be assigned to the specified type, including base classes and interfaces: + ```csharp [Test] public async Task Assignable_To_Base_Or_Interface() @@ -55,6 +58,7 @@ public async Task Assignable_To_Base_Or_Interface() Tests that a value is **not** exactly the specified type: + ```csharp [Test] public async Task Not_Exact_Type() @@ -69,6 +73,7 @@ public async Task Not_Exact_Type() Tests that a value cannot be assigned to the specified type: + ```csharp [Test] public async Task Not_Assignable() @@ -83,6 +88,7 @@ public async Task Not_Assignable() Tests that a value of the specified type can be assigned to a variable of this value's type. This is the reverse of `IsAssignableTo`: + ```csharp [Test] public async Task Assignable_From_Derived() @@ -98,6 +104,7 @@ public async Task Assignable_From_Derived() Tests that a value of the specified type cannot be assigned to a variable of this value's type: + ```csharp [Test] public async Task Not_Assignable_From() @@ -112,6 +119,7 @@ public async Task Not_Assignable_From() Type assertions also work on delegate return values, letting you verify the type returned by a method or lambda: + ```csharp [Test] public async Task Delegate_Return_Type() diff --git a/docs/docs/assertions/types.md b/docs/docs/assertions/types.md index b84aed5ff53..c6f190157b8 100644 --- a/docs/docs/assertions/types.md +++ b/docs/docs/assertions/types.md @@ -14,6 +14,7 @@ TUnit provides comprehensive assertions for testing types and type properties. T Tests that a value is exactly of a specific type: + ```csharp [Test] public async Task Value_Is_Type() @@ -26,6 +27,7 @@ public async Task Value_Is_Type() Works with all types: + ```csharp [Test] public async Task Various_Types() @@ -41,6 +43,7 @@ public async Task Various_Types() Tests that a type can be assigned to a target type (inheritance/interface): + ```csharp [Test] public async Task Type_Is_Assignable() @@ -55,6 +58,7 @@ public async Task Type_Is_Assignable() With inheritance: + ```csharp public class Animal { } public class Dog : Animal { } @@ -74,6 +78,7 @@ public async Task Inheritance_Assignability() Tests that a type cannot be assigned to a target type: + ```csharp [Test] public async Task Type_Not_Assignable() @@ -89,6 +94,7 @@ public async Task Type_Not_Assignable() All the following assertions work on `Type` objects directly: + ```csharp [Test] public async Task Type_Object_Assertions() @@ -104,6 +110,7 @@ public async Task Type_Object_Assertions() #### IsClass / IsNotClass + ```csharp [Test] public async Task Is_Class() @@ -119,6 +126,7 @@ public async Task Is_Class() #### IsInterface / IsNotInterface + ```csharp [Test] public async Task Is_Interface() @@ -134,6 +142,7 @@ public async Task Is_Interface() #### IsAbstract / IsNotAbstract + ```csharp public abstract class AbstractBase { } public class Concrete : AbstractBase { } @@ -148,6 +157,7 @@ public async Task Is_Abstract() #### IsSealed / IsNotSealed + ```csharp public sealed class SealedClass { } public class OpenClass { } @@ -165,6 +175,7 @@ public async Task Is_Sealed() #### IsValueType / IsNotValueType + ```csharp [Test] public async Task Is_Value_Type() @@ -180,6 +191,7 @@ public async Task Is_Value_Type() #### IsEnum / IsNotEnum + ```csharp public enum Color { Red, Green, Blue } @@ -195,6 +207,7 @@ public async Task Is_Enum() #### IsPrimitive / IsNotPrimitive + ```csharp [Test] public async Task Is_Primitive() @@ -214,6 +227,7 @@ public async Task Is_Primitive() #### IsPublic / IsNotPublic + ```csharp public class PublicClass { } internal class InternalClass { } @@ -232,6 +246,7 @@ public async Task Is_Public() #### IsGenericType / IsNotGenericType + ```csharp [Test] public async Task Is_Generic_Type() @@ -245,6 +260,7 @@ public async Task Is_Generic_Type() #### IsGenericTypeDefinition / IsNotGenericTypeDefinition + ```csharp [Test] public async Task Is_Generic_Type_Definition() @@ -260,6 +276,7 @@ public async Task Is_Generic_Type_Definition() #### IsConstructedGenericType / IsNotConstructedGenericType + ```csharp [Test] public async Task Is_Constructed_Generic_Type() @@ -274,6 +291,7 @@ public async Task Is_Constructed_Generic_Type() #### ContainsGenericParameters / DoesNotContainGenericParameters + ```csharp [Test] public async Task Contains_Generic_Parameters() @@ -289,6 +307,7 @@ public async Task Contains_Generic_Parameters() #### IsArray / IsNotArray + ```csharp [Test] public async Task Is_Array() @@ -303,6 +322,7 @@ public async Task Is_Array() #### IsByRef / IsNotByRef + ```csharp [Test] public async Task Is_By_Ref() @@ -317,6 +337,7 @@ public async Task Is_By_Ref() #### IsByRefLike / IsNotByRefLike (.NET 5+) + ```csharp [Test] public async Task Is_By_Ref_Like() @@ -330,6 +351,7 @@ public async Task Is_By_Ref_Like() #### IsPointer / IsNotPointer + ```csharp [Test] public async Task Is_Pointer() @@ -348,6 +370,7 @@ public async Task Is_Pointer() #### IsNested / IsNotNested + ```csharp public class Outer { @@ -364,6 +387,7 @@ public async Task Is_Nested() #### IsNestedPublic / IsNotNestedPublic + ```csharp public class Container { @@ -380,6 +404,7 @@ public async Task Is_Nested_Public() #### IsNestedPrivate / IsNotNestedPrivate + ```csharp [Test] public async Task Is_Nested_Private() @@ -403,6 +428,7 @@ For protected nested types. #### IsVisible / IsNotVisible + ```csharp [Test] public async Task Is_Visible() @@ -426,6 +452,7 @@ public async Task Is_Visible() #### IsCOMObject / IsNotCOMObject + ```csharp [Test] public async Task Is_COM_Object() @@ -439,6 +466,7 @@ public async Task Is_COM_Object() ### Dependency Injection Validation + ```csharp [Test] public async Task Service_Implements_Interface() @@ -452,6 +480,7 @@ public async Task Service_Implements_Interface() ### Plugin System + ```csharp public interface IPlugin { } @@ -468,6 +497,7 @@ public async Task Plugin_Implements_Interface() ### Reflection Testing + ```csharp [Test] public async Task Type_Has_Expected_Properties() @@ -483,6 +513,7 @@ public async Task Type_Has_Expected_Properties() ### Generic Constraints + ```csharp [Test] public async Task Validate_Generic_Constraints() @@ -496,6 +527,7 @@ public async Task Validate_Generic_Constraints() ### Enum Validation + ```csharp [Test] public async Task Type_Is_Enum() @@ -509,6 +541,7 @@ public async Task Type_Is_Enum() ### Abstract Class Validation + ```csharp [Test] public async Task Base_Class_Is_Abstract() @@ -522,6 +555,7 @@ public async Task Base_Class_Is_Abstract() ## Chaining Type Assertions + ```csharp [Test] public async Task Chained_Type_Assertions() @@ -538,6 +572,7 @@ public async Task Chained_Type_Assertions() ## Type Comparison + ```csharp [Test] public async Task Compare_Types() @@ -553,6 +588,7 @@ public async Task Compare_Types() ## Working with Base Types + ```csharp [Test] public async Task Check_Base_Type() @@ -566,6 +602,7 @@ public async Task Check_Base_Type() ## Interface Implementation + ```csharp [Test] public async Task Implements_Multiple_Interfaces() @@ -582,6 +619,7 @@ public async Task Implements_Multiple_Interfaces() ### Factory Pattern Validation + ```csharp [Test] public async Task Factory_Returns_Correct_Type() @@ -595,6 +633,7 @@ public async Task Factory_Returns_Correct_Type() ### ORM Entity Validation + ```csharp [Test] public async Task Entity_Is_Properly_Configured() @@ -612,6 +651,7 @@ public async Task Entity_Is_Properly_Configured() ### Serialization Requirements + ```csharp [Test] public async Task Type_Is_Serializable() @@ -629,6 +669,7 @@ public async Task Type_Is_Serializable() ### Test Double Validation + ```csharp [Test] public async Task Mock_Implements_Interface() @@ -642,6 +683,7 @@ public async Task Mock_Implements_Interface() ## Struct Validation + ```csharp public struct Point { @@ -662,6 +704,7 @@ public async Task Struct_Properties() ## Record Validation + ```csharp public record Person(string Name, int Age); diff --git a/docs/docs/benchmarks/methodology.md b/docs/docs/benchmarks/methodology.md index 790ee77072b..3907dd66444 100644 --- a/docs/docs/benchmarks/methodology.md +++ b/docs/docs/benchmarks/methodology.md @@ -41,6 +41,7 @@ All benchmarks use [BenchmarkDotNet](https://benchmarkdotnet.org/), the industry **Purpose**: Measure parameterized test performance **What's tested**: + ```csharp [Test] [Arguments(1, 2, 3)] @@ -60,6 +61,7 @@ public async Task TestAddition(int a, int b, int expected) **Purpose**: Measure async/await pattern performance **What's tested**: + ```csharp [Test] public async Task TestAsyncOperation() @@ -89,6 +91,7 @@ public async Task TestAsyncOperation() **Purpose**: Measure combinatorial test generation **What's tested**: + ```csharp [Test] [MatrixDataSource] @@ -157,6 +160,7 @@ dotnet build -c Release -p:TestFramework=MSTEST ``` ### 2. Execution Phase + ```csharp using BenchmarkDotNet.Attributes; diff --git a/docs/docs/comparison/framework-differences.md b/docs/docs/comparison/framework-differences.md index 91663b7d901..838f84a579a 100644 --- a/docs/docs/comparison/framework-differences.md +++ b/docs/docs/comparison/framework-differences.md @@ -45,6 +45,7 @@ In TUnit, you can inject a `TestContext` into your teardown method, or call `Tes xUnit assertions have the classic problem of unclear argument order: + ```csharp var one = 2; Assert.Equal(1, one); // is 1 the expected or actual? @@ -97,6 +98,7 @@ In other frameworks, running tests in a specific order usually means disabling p TUnit has `[DependsOn(...)]` — a test waits for its dependencies to finish, without disabling parallelism for everything else: + ```csharp [Test] public async Task Test1() { ... } diff --git a/docs/docs/execution/cancellation.md b/docs/docs/execution/cancellation.md index e89e3fb6698..ee8837dfc2c 100644 --- a/docs/docs/execution/cancellation.md +++ b/docs/docs/execution/cancellation.md @@ -4,6 +4,7 @@ Call `TestContext.Execution.Cancel()` to request cooperative cancellation of the current test without affecting other tests or the test session: + ```csharp [Test] public async Task ProcessMessages(CancellationToken cancellationToken) diff --git a/docs/docs/execution/parameters.md b/docs/docs/execution/parameters.md index 73c6febee68..539240d3d84 100644 --- a/docs/docs/execution/parameters.md +++ b/docs/docs/execution/parameters.md @@ -51,6 +51,7 @@ public class MyTests ### Environment-specific configuration + ```csharp [Before(Test)] public void SetupEnvironment() @@ -64,6 +65,7 @@ public void SetupEnvironment() ### Conditional test logic + ```csharp [Test] public async Task IntegrationTest() @@ -79,6 +81,7 @@ public async Task IntegrationTest() ### Passing secrets or connection strings + ```csharp [Test] public async Task DatabaseTest() diff --git a/docs/docs/execution/timeouts.md b/docs/docs/execution/timeouts.md index f00ef2e0b56..abb0f7e579d 100644 --- a/docs/docs/execution/timeouts.md +++ b/docs/docs/execution/timeouts.md @@ -42,6 +42,7 @@ If the HTTP call takes longer than 30 seconds, `cancellationToken` is cancelled, When a test has both `[Timeout]` and `[Retry]`, each retry attempt gets its own fresh timeout. If the first attempt times out at 5 seconds, the retry starts from zero with a new 5-second window: + ```csharp [Test] [Timeout(5_000)] diff --git a/docs/docs/extending/exception-handling.md b/docs/docs/extending/exception-handling.md index df164b06322..7e2ac14f89b 100644 --- a/docs/docs/extending/exception-handling.md +++ b/docs/docs/extending/exception-handling.md @@ -8,6 +8,7 @@ When a test fails, TUnit throws an exception. Most of the time you don't need to If a test can't run because of some runtime condition, throw `SkipTestException`. The test will be reported as skipped rather than failed. + ```csharp [Test] public async Task RequiresExternalService() @@ -25,6 +26,7 @@ public async Task RequiresExternalService() If a test can't determine a pass/fail result, throw `InconclusiveTestException`. + ```csharp [Test] public async Task CheckFeatureFlag() @@ -44,6 +46,7 @@ public async Task CheckFeatureFlag() In an `[After(Test)]` hook, you can check whether the test failed via `TestContext`: + ```csharp [After(Test)] public async Task TakeScreenshotOnFailure(TestContext context) diff --git a/docs/docs/getting-started/writing-your-first-test.md b/docs/docs/getting-started/writing-your-first-test.md index 3c34ee9bc80..528e6364c1a 100644 --- a/docs/docs/getting-started/writing-your-first-test.md +++ b/docs/docs/getting-started/writing-your-first-test.md @@ -81,6 +81,7 @@ Tests will pass if they execute successfully without any exceptions. Test methods can be either synchronous or asynchronous: + ```csharp [Test] public void SynchronousTest() // ✅ Valid - synchronous test diff --git a/docs/docs/guides/distributed-tracing.md b/docs/docs/guides/distributed-tracing.md index c78ec0a2bbe..40b949ce2e4 100644 --- a/docs/docs/guides/distributed-tracing.md +++ b/docs/docs/guides/distributed-tracing.md @@ -113,6 +113,7 @@ TUnit handles this automatically: a module initializer in `TUnit.Core` replaces For the SUT side, if it shares the test process (e.g. `TestWebApplicationFactory`), alignment flows automatically. For out-of-process SUTs that don't reference `TUnit.Core`, align the propagator yourself on startup — either match `DistributedContextPropagator.Current` or, if you use the OpenTelemetry SDK: + ```csharp using OpenTelemetry; using OpenTelemetry.Context.Propagation; @@ -171,6 +172,7 @@ Install [`TUnit.OpenTelemetry`](/docs/examples/opentelemetry#option-a-zero-confi Read the endpoint from `AutoReceiver.Endpoint` and plumb it into the SUT: + ```csharp using TUnit.OpenTelemetry; @@ -181,6 +183,7 @@ process.StartInfo.EnvironmentVariables["OTEL_EXPORTER_OTLP_PROTOCOL"] = "http/pr For the receiver to associate incoming spans with the right test, register the SUT's trace ID before it runs: + ```csharp using TUnit.Engine.Reporters.Html; diff --git a/docs/docs/guides/html-report.md b/docs/docs/guides/html-report.md index 4539d079221..251b21bd3c9 100644 --- a/docs/docs/guides/html-report.md +++ b/docs/docs/guides/html-report.md @@ -158,6 +158,7 @@ TUnit's test body runs under a per-test `System.Diagnostics.Activity`. Because ` For example, an integration test using `WebApplicationFactory`: + ```csharp [Test] public async Task GetUsers_ReturnsOk() @@ -179,6 +180,7 @@ The HTML report groups each test under its class. Backends like Seq, Jaeger, and If your test communicates with an external service that runs in a **separate process** (and therefore has a different trace context), you can manually link its trace to the test: + ```csharp [Test] public async Task ProcessOrder_SendsNotification() @@ -199,6 +201,7 @@ Linked traces appear as a separate **"Linked Trace"** section below the test's m You can access the current test's `Activity` to parent external work explicitly: + ```csharp [Test] public async Task MyTest() diff --git a/docs/docs/guides/philosophy.md b/docs/docs/guides/philosophy.md index 1c8538309f9..d5a766a8464 100644 --- a/docs/docs/guides/philosophy.md +++ b/docs/docs/guides/philosophy.md @@ -10,6 +10,7 @@ Most frameworks make you opt into parallelism. TUnit flips that — tests run in This also nudges you toward better test design. If your tests can't run in parallel, they're probably sharing state they shouldn't be. When they genuinely do need exclusive access to something (a shared file, a database, a hardware device), you opt out explicitly: + ```csharp [Test, NotInParallel] public async Task ModifiesSharedConfigFile() { ... } @@ -25,6 +26,7 @@ If you need shared state, use `static`. That makes the sharing visible to anyone All assertions return `Task` and must be awaited. This is probably TUnit's most controversial decision. + ```csharp await Assert.That(result).IsEqualTo(expected); ``` @@ -47,6 +49,7 @@ The trade-off is that some older tools only work with VSTest — Coverlet being TUnit's assertions are extension methods on specific types, not generic methods that accept anything. Intellisense only shows assertions that make sense for what you're testing. You can't accidentally check if a string is negative, because that method doesn't exist on strings. + ```csharp await Assert.That(user.Email) .IsNotNull() diff --git a/docs/docs/reference/programmatic-configuration.md b/docs/docs/reference/programmatic-configuration.md index 541d36ee129..07ab47d89ae 100644 --- a/docs/docs/reference/programmatic-configuration.md +++ b/docs/docs/reference/programmatic-configuration.md @@ -95,6 +95,7 @@ When the same setting is configured in multiple places, the following priority o Your test project sets a conservative parallelism limit in code: + ```csharp context.Settings.Parallelism.MaximumParallelTests = 1; ``` diff --git a/docs/docs/writing-tests/artifacts.md b/docs/docs/writing-tests/artifacts.md index edb507f92bf..8e023a24e0d 100644 --- a/docs/docs/writing-tests/artifacts.md +++ b/docs/docs/writing-tests/artifacts.md @@ -18,6 +18,7 @@ Use `TestContext.ResultsDirectory` to place generated files alongside reports an artifacts. The property returns the absolute directory selected by Microsoft.Testing.Platform, including any `--results-directory` override. + ```csharp [Test] public async Task CaptureLog() @@ -33,6 +34,7 @@ public async Task CaptureLog() The simplest way to attach an artifact is by providing just the file path: + ```csharp [Test] public async Task MyIntegrationTest() @@ -56,6 +58,7 @@ public async Task MyIntegrationTest() For more control, you can create an `Artifact` object directly: + ```csharp [Test] public async Task MyIntegrationTest() @@ -110,6 +113,7 @@ public class MyTests You can attach multiple artifacts to a single test: + ```csharp [Test] public async Task ComplexIntegrationTest() @@ -149,6 +153,7 @@ Attach files to the entire test session using `TestSessionContext.Current.AddArt ### Basic Usage + ```csharp [Before(TestSession)] public static void SetupTestSession() @@ -171,6 +176,7 @@ public static void SetupTestSession() Attach configuration files to document the test environment: + ```csharp [Before(TestSession)] public static void DocumentTestEnvironment() @@ -200,6 +206,7 @@ public static void DocumentTestEnvironment() Generate and attach performance reports for the entire test session: + ```csharp [After(TestSession)] public static void GeneratePerformanceReport() @@ -240,6 +247,7 @@ public class Artifact Consider cleaning up temporary artifact files after test execution to avoid accumulating files: + ```csharp [After(TestSession)] public static void CleanupArtifacts() @@ -256,6 +264,7 @@ public static void CleanupArtifacts() Create a unique directory for each test's artifacts: + ```csharp [Before(Test)] public void SetupTestArtifactDirectory() @@ -288,6 +297,7 @@ public void MyTest() For large artifacts (videos, extensive logs), consider only attaching them when tests fail: + ```csharp [After(Test)] public async Task ConditionalArtifactAttachment() @@ -313,6 +323,7 @@ public async Task ConditionalArtifactAttachment() Provide clear, descriptive names and descriptions for your artifacts: + ```csharp // ❌ Not descriptive TestContext.Current!.Output.AttachArtifact(new Artifact @@ -334,6 +345,7 @@ TestContext.Current!.Output.AttachArtifact(new Artifact Always ensure the file exists before attaching: + ```csharp var logPath = "path/to/logfile.log"; @@ -355,6 +367,7 @@ else ### Browser Testing with Playwright + ```csharp [After(Test)] public async Task CapturePlaywrightArtifacts() @@ -391,6 +404,7 @@ public async Task CapturePlaywrightArtifacts() ### API Testing + ```csharp [Test] public async Task ApiIntegrationTest() @@ -426,6 +440,7 @@ public async Task ApiIntegrationTest() ### Database Testing + ```csharp [Test] public async Task DatabaseIntegrationTest() diff --git a/docs/docs/writing-tests/hooks.md b/docs/docs/writing-tests/hooks.md index 8ac34b10d13..923b526343c 100644 --- a/docs/docs/writing-tests/hooks.md +++ b/docs/docs/writing-tests/hooks.md @@ -10,6 +10,7 @@ For the full execution order, see [Test Lifecycle](lifecycle.md). Hook methods can be synchronous or asynchronous: + ```csharp [Before(Test)] public void SynchronousSetup() // ✅ Valid @@ -43,6 +44,7 @@ public async Task AsyncCleanup() // ✅ Valid Hooks can optionally accept a context object and/or a `CancellationToken`: + ```csharp [Before(Test)] public async Task Setup(TestContext context, CancellationToken cancellationToken) @@ -72,6 +74,7 @@ public async Task Setup(TestContext context, CancellationToken cancellationToken A common pattern in `[After]` hooks is checking whether the test failed: + ```csharp [After(Test)] public async Task Cleanup(TestContext context, CancellationToken cancellationToken) @@ -214,6 +217,7 @@ public class MyTestClass Setting `AsyncLocal` values in `[Before]` hooks is supported. Call `context.AddAsyncLocalValues()` to propagate them into the test framework: + ```csharp [BeforeEvery(Class)] public static void BeforeClass(ClassHookContext context) diff --git a/docs/docs/writing-tests/mocking/http.md b/docs/docs/writing-tests/mocking/http.md index c87387dc397..6989350ea24 100644 --- a/docs/docs/writing-tests/mocking/http.md +++ b/docs/docs/writing-tests/mocking/http.md @@ -14,6 +14,7 @@ dotnet add package TUnit.Mocks.Http ## Getting Started + ```csharp using TUnit.Mocks; @@ -38,6 +39,7 @@ public async Task Fetches_Users_From_Api() `Mock.HttpClient()` returns a `MockHttpClient` — a subclass of `HttpClient` with a `.Handler` property for configuring setups and verifying calls: + ```csharp // With base address (most common) using var client = Mock.HttpClient("https://api.example.com"); @@ -59,6 +61,7 @@ All setup is done through `client.Handler` (or directly on a `MockHttpHandler` i ### By HTTP Method + ```csharp client.Handler.OnGet("/api/users").RespondWithJson("""[{"id": 1}]"""); client.Handler.OnPost("/api/users").Respond(HttpStatusCode.Created); @@ -68,6 +71,7 @@ client.Handler.OnDelete("/api/users/1").Respond(HttpStatusCode.NoContent); ### Any Request + ```csharp client.Handler.OnAnyRequest().Respond(HttpStatusCode.OK); ``` @@ -76,6 +80,7 @@ client.Handler.OnAnyRequest().Respond(HttpStatusCode.OK); Use `OnRequest` with a fluent matcher for complex conditions: + ```csharp // Match by path prefix client.Handler.OnRequest(r => r.Method(HttpMethod.Get).PathStartsWith("/api/v2")) @@ -118,6 +123,7 @@ client.Handler.OnRequest(r => r.Matching(msg => msg.RequestUri?.Port == 8080)) ### Basic Responses + ```csharp // Status code only client.Handler.OnGet("/health").Respond(HttpStatusCode.OK); @@ -133,6 +139,7 @@ client.Handler.OnGet("/api/version").RespondWithString("1.0.0"); For more control, use the response builder: + ```csharp client.Handler.OnGet("/api/data") .Respond(HttpStatusCode.OK) @@ -144,6 +151,7 @@ client.Handler.OnGet("/api/data") Build responses based on the incoming request: + ```csharp client.Handler.OnPost("/api/echo") .Respond() @@ -159,6 +167,7 @@ client.Handler.OnPost("/api/echo") ### Simulating Delays + ```csharp client.Handler.OnGet("/api/slow") .Respond(HttpStatusCode.OK) @@ -167,6 +176,7 @@ client.Handler.OnGet("/api/slow") ### Throwing Exceptions + ```csharp client.Handler.OnGet("/api/failing") .Throws("Connection refused"); @@ -179,6 +189,7 @@ client.Handler.OnGet("/api/timeout") Return different responses for successive requests to the same endpoint: + ```csharp var setup = client.Handler.OnGet("/api/status"); setup.RespondWithString("starting"); @@ -194,6 +205,7 @@ setup.Then().RespondWithString("complete"); By default, unmatched requests return **404 Not Found**. You can change this: + ```csharp // Change default status code client.Handler.WithDefaultStatus(HttpStatusCode.ServiceUnavailable); @@ -206,6 +218,7 @@ client.Handler.ThrowOnUnmatched(); ### Verify Call Count + ```csharp client.Handler.Verify(r => r.Method(HttpMethod.Get).Path("/api/users"), Times.Once); client.Handler.Verify(r => r.Method(HttpMethod.Delete), Times.Never); @@ -213,12 +226,14 @@ client.Handler.Verify(r => r.Method(HttpMethod.Delete), Times.Never); ### Verify No Unmatched Requests + ```csharp client.Handler.VerifyNoUnmatchedRequests(); ``` ### Inspect Captured Requests + ```csharp await Assert.That(client.Handler.Requests).Count().IsEqualTo(2); await Assert.That(client.Handler.Requests[0].Method).IsEqualTo(HttpMethod.Get); @@ -243,6 +258,7 @@ Each `CapturedRequest` provides: `Mock.HttpClientFactory()` returns a factory whose `CreateClient` produces non-disposing `HttpClient`s sharing one `MockHttpHandler`, so captured requests survive `using` blocks in the system under test. + ```csharp var factory = Mock.HttpClientFactory().WithBaseAddress("https://api.example.com"); factory.Handler.OnGet("/api/users").RespondWithJson("""[{"id":1}]"""); @@ -257,6 +273,7 @@ factory.Handler.Verify(r => r.Method(HttpMethod.Get).Path("/api/users"), Times.O For typed/named clients registered via `services.AddHttpClient("users")`, assign a dedicated handler (and optionally base address) per name. Name lookups are case-insensitive, matching `IHttpClientFactory` semantics. Unregistered names fall back to `factory.Handler`. + ```csharp var factory = Mock.HttpClientFactory() .WithHandler("users", Mock.HttpHandler()) @@ -270,6 +287,7 @@ factory.HandlerFor("orders").OnPost("/").Respond(HttpStatusCode.Created); ## Reset + ```csharp client.Handler.Reset(); // clears all setups and captured requests ``` diff --git a/docs/docs/writing-tests/mocking/index.md b/docs/docs/writing-tests/mocking/index.md index 58ab6f8d9f2..1de27cf1335 100644 --- a/docs/docs/writing-tests/mocking/index.md +++ b/docs/docs/writing-tests/mocking/index.md @@ -67,6 +67,7 @@ public class GreeterTests The `Mock.Of()` factory is also available as an alternative syntax: + ```csharp var mock = Mock.Of(); // equivalent to IGreeter.Mock() ``` @@ -89,6 +90,7 @@ var mock = Mock.Of(); // equivalent to IGreeter.Mock() All factory methods accept an optional `MockBehavior` parameter: + ```csharp var loose = IService.Mock(); // loose (default) var strict = IService.Mock(MockBehavior.Strict); // throws on unconfigured calls @@ -114,6 +116,7 @@ public class GlobalSetup With this setting, `IService.Mock()`, `Mock.Of()`, `Mock.Wrap(instance)`, `Mock.OfDelegate()`, and `new MockRepository()` use strict mode by default. Passing a `MockBehavior` still overrides the global default: + ```csharp var strict = IService.Mock(); // uses global strict default var loose = IService.Mock(MockBehavior.Loose); // explicit override @@ -123,6 +126,7 @@ var loose = IService.Mock(MockBehavior.Loose); // explicit override `T.Mock()` returns a `Mock` wrapper (for interfaces, a generated subclass that also implements the interface). Extension methods are generated directly on `Mock` for each member of the mocked type, and the chain methods (`.Returns()`, `.WasCalled()`, etc.) disambiguate between setup and verification: + ```csharp var mock = IService.Mock(); @@ -136,6 +140,7 @@ _ = mock.Object; // the T instance (also available vi For interfaces, `IMyInterface.Mock()` (a C# 14 static extension member) returns a specialized wrapper type that extends `Mock` **and** implements the interface directly. This means the mock can be used anywhere the interface is expected — no `.Object` or cast needed: + ```csharp var mock = IGreeter.Mock(); @@ -151,6 +156,7 @@ mock.Greet("Alice").WasCalled(); `T.Mock()` is the recommended syntax for all types — interfaces, abstract classes, and concrete classes. For interfaces it returns a typed wrapper; for classes it returns `Mock`. Constructor arguments are supported as strongly-typed parameters: + ```csharp var strict = IGreeter.Mock(MockBehavior.Strict); var service = MyService.Mock("connectionString", 42); @@ -164,6 +170,7 @@ var service = MyService.Mock("connectionString", 42); `Mock` also supports implicit conversion to `T` — so `T.Mock()` works without `.Object`: + ```csharp var mock = IGreeter.Mock(); IGreeter greeter = mock; // implicit conversion @@ -180,6 +187,7 @@ IGreeter greeter = mock; // implicit conversion TUnit.Mocks imports matchers globally — no `Arg.` prefix needed. Raw values, inline lambdas, and `Any()` work directly as arguments: + ```csharp var mock = IUserService.Mock(); diff --git a/docs/docs/writing-tests/mocking/logging.md b/docs/docs/writing-tests/mocking/logging.md index 1a787d68d12..a326a34c62e 100644 --- a/docs/docs/writing-tests/mocking/logging.md +++ b/docs/docs/writing-tests/mocking/logging.md @@ -18,6 +18,7 @@ Unlike `TUnit.Mocks`, the logging helpers are plain classes — no source genera ## Getting Started + ```csharp using TUnit.Mocks; using Microsoft.Extensions.Logging; @@ -39,6 +40,7 @@ public async Task Service_Logs_On_Startup() ## Creating a Logger + ```csharp // Untyped logger var logger = Mock.Logger(); @@ -54,6 +56,7 @@ ILogger iLogger = logger; ## Inspecting Entries + ```csharp logger.LogInformation("User {UserId} logged in", 42); logger.LogWarning("Disk space low"); @@ -85,6 +88,7 @@ Each `LogEntry` provides: Build verification queries with filters: + ```csharp // By level logger.VerifyLog().AtLevel(LogLevel.Error).WasCalled(Times.Once); @@ -108,6 +112,7 @@ logger.VerifyLog() ### Shorthand Methods + ```csharp // Verify message at level (at least once) logger.VerifyLog(LogLevel.Error, "connection failed"); @@ -124,6 +129,7 @@ logger.VerifyNoLogs(); ### Never Called + ```csharp logger.VerifyLog().AtLevel(LogLevel.Error).WasNeverCalled(); ``` @@ -132,6 +138,7 @@ logger.VerifyLog().AtLevel(LogLevel.Error).WasNeverCalled(); Retrieve entries matching specific criteria: + ```csharp // By level var errors = logger.GetLogs(LogLevel.Error); @@ -148,6 +155,7 @@ var matching = logger.VerifyLog() ## Reset + ```csharp logger.Clear(); // removes all captured entries ``` @@ -156,6 +164,7 @@ logger.Clear(); // removes all captured entries Pass `Mock.Logger()` anywhere `ILogger` is expected: + ```csharp [Test] public async Task OrderService_Logs_Errors() diff --git a/docs/docs/writing-tests/mocking/setup.md b/docs/docs/writing-tests/mocking/setup.md index 56d9f1860a8..26b8b1d75f4 100644 --- a/docs/docs/writing-tests/mocking/setup.md +++ b/docs/docs/writing-tests/mocking/setup.md @@ -12,6 +12,7 @@ Methods are called directly on `Mock` — the chain method (`.Returns()`, `.T ### Return Values + ```csharp // Fixed return value mock.GetUser(Any()).Returns(new User("Alice")); @@ -26,6 +27,7 @@ mock.GetUserAsync(Any()).Returns(new User("Alice")); ### Throwing Exceptions + ```csharp // Throw a specific exception type mock.Delete(Any()).Throws(); @@ -36,6 +38,7 @@ mock.Delete(Any()).Throws(new ArgumentException("bad id")); ### Callbacks + ```csharp // Simple callback var callCount = 0; @@ -51,6 +54,7 @@ mock.Process(Any()) Use `.Then()` to define different behaviors for successive calls: + ```csharp mock.GetValue(Any()) .Throws() // 1st call: throws @@ -68,6 +72,7 @@ mock.GetValue(Any()) Chained setup behaviors without `.Then()` run together as a single invocation step. When multiple return behaviors are chained in one step, the last return wins: + ```csharp mock.GetValue(Any()) .Returns("first") @@ -82,6 +87,7 @@ different invocation. Void methods support `Callback` and `Throws` (but not `Returns`): + ```csharp mock.Log(Any()) .Callback(() => { /* side effect */ }); @@ -98,6 +104,7 @@ TUnit.Mocks uses C# 14 extension properties for a natural property API. The defa ### Getter Setup + ```csharp // These are equivalent — both configure the getter mock.Name.Returns("Alice"); @@ -106,6 +113,7 @@ mock.Name.Getter.Returns("Alice"); All method setup operations work on getters: + ```csharp mock.Name.Throws(); mock.Name.Callback(() => Console.WriteLine("Name accessed")); @@ -114,6 +122,7 @@ mock.Name.ReturnsSequentially("first", "second"); ### Setter Setup + ```csharp // React to any value being set mock.Count.Setter.Callback(() => Console.WriteLine("Count was set")); @@ -129,6 +138,7 @@ mock.Name.Setter.Throws(); Call `SetupAllProperties()` to make properties behave like real auto-properties — setters store values, getters return them: + ```csharp var mock = IEntity.Mock(); mock.SetupAllProperties(); @@ -146,6 +156,7 @@ Explicit setups take precedence over auto-tracked values. **Out parameters** are excluded from setup signatures. Use the generated strongly-typed `.SetsOut{Name}()` methods to assign their values: + ```csharp // Strongly-typed — named after the parameter, compile-time safe mock.TryGet("key") @@ -158,6 +169,7 @@ bool found = svc.TryGet("key", out var value); **Ref parameters** are included in setup signatures and participate in argument matching. Use `.SetsRef{Name}()` to assign output values: + ```csharp mock.Swap(Any()) .SetsRefValue(99); @@ -191,6 +203,7 @@ mock.Object.Multiply(2, 3); // 99 (mocked) Pass constructor arguments for non-default constructors: + ```csharp var mock = MyService.Mock("connectionString", 42); ``` @@ -223,6 +236,7 @@ The bridge type implements all the non-static members of the original interface, Mock any delegate type: + ```csharp var mock = Mock.OfDelegate>(); mock.Invoke(Any()).Returns(42); @@ -237,6 +251,7 @@ Works with `Action<>`, `Func<>`, and custom delegate types. Wrap a real instance to selectively override methods while delegating unconfigured calls to the real implementation: + ```csharp var realService = new ProductionService(); var mock = Mock.Wrap(realService); @@ -252,6 +267,7 @@ mock.Object.DoWork(); // calls realService.DoWork() Create a single mock that implements multiple interfaces: + ```csharp var mock = Mock.Of(); @@ -265,6 +281,7 @@ Supports up to 4 interfaces: `Mock.Of()`. Members of the secondary interfaces appear directly on the mock, just like the primary's — setup, verify, and event raising all work the same way: + ```csharp var mock = Mock.Of(); @@ -276,6 +293,7 @@ When a secondary member's name collides with a member of another interface on th The primary type can also be a concrete class — useful for types like EF Core's `DbContext` that implement infrastructure interfaces explicitly: + ```csharp var mock = Mock.Of>(); mock.Instance.Returns(serviceProvider); @@ -289,6 +307,7 @@ Constructor arguments for class primaries are supported: `Mock.Of ```csharp mock.Process(Any()) .Returns(true) diff --git a/docs/docs/writing-tests/mocking/verification.md b/docs/docs/writing-tests/mocking/verification.md index 13d3b508095..e5b99412d1c 100644 --- a/docs/docs/writing-tests/mocking/verification.md +++ b/docs/docs/writing-tests/mocking/verification.md @@ -10,6 +10,7 @@ Verification uses the same methods as setup — the chain method (`.WasCalled()` ## Basic Verification + ```csharp // Verify a method was called at least once mock.GetUser(42).WasCalled(); @@ -35,6 +36,7 @@ mock.Delete(Any()).WasNeverCalled(); ### Custom Failure Messages + ```csharp mock.GetUser(42).WasCalled(Times.Once, "GetUser should be called once during initialization"); mock.Delete(Any()).WasNeverCalled("Delete should not be called in read-only mode"); @@ -44,6 +46,7 @@ mock.Delete(Any()).WasNeverCalled("Delete should not be called in read-only mode Property verification mirrors the setup API — defaults to the **getter**: + ```csharp // Getter verification mock.Name.WasCalled(Times.Once); // getter called once @@ -63,6 +66,7 @@ mock.Count.Set(v => v > 0).WasCalled(Times.AtLeast(1)); Verification uses the same `Arg` matchers as setup: + ```csharp // Exact value mock.GetUser(42).WasCalled(Times.Once); @@ -80,6 +84,7 @@ See [Argument Matchers](argument-matchers) for the full list of matchers. Verify calls occurred in a specific order **across one or more mocks**: + ```csharp Mock.VerifyInOrder(() => { @@ -99,6 +104,7 @@ If calls occurred out of order, `VerifyInOrder` throws with a message showing th Verify that **every setup** was invoked at least once: + ```csharp mock.GetUser(Any()).Returns(new User("Alice")); mock.Delete(Any()); @@ -115,6 +121,7 @@ If any setup was never called, `VerifyAll` throws listing the uninvoked setups. Verify that all recorded calls have been explicitly verified: + ```csharp svc.GetUser(1); svc.Delete(2); @@ -131,6 +138,7 @@ If there are unverified calls, `VerifyNoOtherCalls` throws listing them. Use TUnit's `Assert.That` pipeline for assertion-style verification with better error messages: + ```csharp using TUnit.Mocks.Assertions; @@ -147,6 +155,7 @@ This integrates with TUnit's assertion engine — failures appear as assertion e Access the raw call history for custom inspection: + ```csharp var calls = mock.Invocations; diff --git a/docs/docs/writing-tests/ordering.md b/docs/docs/writing-tests/ordering.md index 3fa37c9823f..eef6e34dfdb 100644 --- a/docs/docs/writing-tests/ordering.md +++ b/docs/docs/writing-tests/ordering.md @@ -59,6 +59,7 @@ If you have multiple tests with the same name, but different parameter types, th ::: e.g.: + ```csharp public void Test1(string value1, int value2) { ... } @@ -70,6 +71,7 @@ This means you can create more complex test suites, without having to compromise For example, performing some operations on a database and asserting a count at the end: + ```csharp [Test] public async Task AddUser1() @@ -145,6 +147,7 @@ Use argument values or other properties to select the specific test context you Example: + ```csharp [Test] public async Task AddItemToBag() @@ -167,6 +170,7 @@ public async Task DeleteItemFromBag() If your test depends on another test, by default, if that dependency fails, then your test that depends on it will not start. This can be bypassed by adding the property `ProceedOnFailure = true` to the `DependsOnAttribute`. Your test suite will still fail due to that test, but it allows you to proceed with other tests if you require it. For example, CRUD testing, and wanting to perform a delete after all your other tests, regardless of if they passed. + ```csharp [Test] public async Task Test1() diff --git a/tools/TUnit.DocSnippetGenerator/Program.cs b/tools/TUnit.DocSnippetGenerator/Program.cs index c45d72311cc..5ee97ec96ca 100644 --- a/tools/TUnit.DocSnippetGenerator/Program.cs +++ b/tools/TUnit.DocSnippetGenerator/Program.cs @@ -50,7 +50,7 @@ } Console.WriteLine($"Generated {snippets.Count} C# documentation snippets."); -Console.WriteLine($"Skipped {contextualSnippets} snippets declared contextual by {contextualFiles.Count} files, {excludedSnippets} explicit snippets, and {excludedFiles} files."); +Console.WriteLine($"Skipped {contextualSnippets} explicitly contextual snippets declared by {contextualFiles.Count} files, {excludedSnippets} explicit snippets, and {excludedFiles} files."); Console.WriteLine($"Documented TUnit packages: {string.Join(", ", documentedPackages.Order())}"); return 0; @@ -131,14 +131,22 @@ void ReadDocument(string documentPath) var explicitMode = Regex.Match(directive, "^$"); var splitMode = Regex.Match(directive, "^$"); + var contextualMode = Regex.IsMatch(directive, "^$"); if (directive.StartsWith(" @@ -146,6 +147,13 @@ Use a directive immediately before a fence when its context needs to be explicit Use `` on each fence that depends on surrounding prose. Its page must declare ``, so unmarked fences still compile and cannot be silently excluded by page-level configuration. Use `` when no snippets on a page can compile independently. File directives require a reason. +For a fence that mixes declarations or members with usage, split it explicitly at an exact marker: + +```markdown + + +``` + Run the check against local packages with: ```powershell diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index e01fd20f8b5..386f539e12b 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -172,7 +172,7 @@ jobs: - name: Compile documentation snippets if: matrix.os == 'ubuntu-latest' shell: pwsh - run: ./scripts/Verify-DocSnippets.ps1 -PackagesPath . -Version $env:Version + run: ./scripts/Verify-DocSnippets.ps1 -PackagesPath . -Version $env:PackageVersion - name: Upload Diagnostic Logs uses: actions/upload-artifact@v7.0.1 diff --git a/docs/docs/examples/opentelemetry.md b/docs/docs/examples/opentelemetry.md index 377788a46e6..6c9113cd44e 100644 --- a/docs/docs/examples/opentelemetry.md +++ b/docs/docs/examples/opentelemetry.md @@ -76,7 +76,6 @@ Then subscribe to the `"TUnit"` ActivitySource in a `[Before(TestDiscovery)]` ho using System.Diagnostics; using OpenTelemetry; using OpenTelemetry.Trace; -using OpenTelemetry.Trace; using OpenTelemetry.Resources; public class TraceSetup @@ -327,6 +326,11 @@ For manual setups, add this processor to your tracer builder: using System.Diagnostics; using OpenTelemetry; +// Usage: +using var tracerProvider = Sdk.CreateTracerProviderBuilder() + .AddProcessor(new TUnitTagProcessor()) + .Build(); + public sealed class TUnitTagProcessor : BaseProcessor { public override void OnStart(Activity activity) @@ -338,11 +342,6 @@ public sealed class TUnitTagProcessor : BaseProcessor } } } - -// 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. diff --git a/tests/TUnit.DocTests/Program.cs b/tests/TUnit.DocTests/Program.cs index eb2b6a022df..bed7b17c914 100644 --- a/tests/TUnit.DocTests/Program.cs +++ b/tests/TUnit.DocTests/Program.cs @@ -4,7 +4,6 @@ namespace TUnit.DocTests; internal abstract class SnippetContext { - protected static readonly CancellationToken CancellationToken = default; protected static readonly CancellationToken cancellationToken = default; protected static readonly CancellationToken ct = default; } diff --git a/tests/TUnit.DocTests/TUnit.DocTests.csproj b/tests/TUnit.DocTests/TUnit.DocTests.csproj index 27c60112a2b..81a740e6868 100644 --- a/tests/TUnit.DocTests/TUnit.DocTests.csproj +++ b/tests/TUnit.DocTests/TUnit.DocTests.csproj @@ -17,7 +17,7 @@ - + @@ -49,7 +49,12 @@ - + + + + + diff --git a/tools/TUnit.DocSnippetGenerator/Program.cs b/tools/TUnit.DocSnippetGenerator/Program.cs index 5ee97ec96ca..564e23e4593 100644 --- a/tools/TUnit.DocSnippetGenerator/Program.cs +++ b/tools/TUnit.DocSnippetGenerator/Program.cs @@ -375,8 +375,15 @@ static string GenerateSource(Snippet snippet, int index, ISet emittedAss return builder.ToString(); } + if (snippet.Mode == SnippetMode.Statements && snippet.SplitBefore is not null) + { + throw new InvalidOperationException( + $"Statement snippet {snippet.SourcePath}:{snippet.Line} cannot have a split marker."); + } + var memberSource = source; string? statementSource = null; + var splitStatementLine = snippet.Line; if (snippet.SplitBefore is not null) { var splitIndex = source.IndexOf(snippet.SplitBefore, StringComparison.Ordinal); @@ -388,9 +395,16 @@ static string GenerateSource(Snippet snippet, int index, ISet emittedAss memberSource = source[..splitIndex].TrimEnd(); statementSource = source[splitIndex..]; + splitStatementLine += source[..splitIndex].Count(character => character == '\n'); } var containsExtensionMethod = Regex.IsMatch(memberSource, @"(?:\(|,)\s*this\s+[A-Za-z_]"); + if (snippet.Mode == SnippetMode.Statements && containsExtensionMethod) + { + throw new InvalidOperationException( + $"Statement snippet {snippet.SourcePath}:{snippet.Line} cannot contain an extension method."); + } + builder.AppendLine($"namespace {generatedNamespace};"); if (containsExtensionMethod) @@ -441,10 +455,9 @@ static string GenerateSource(Snippet snippet, int index, ISet emittedAss if (statementSource is not null) { - var statementLine = snippet.Line + source[..source.IndexOf(snippet.SplitBefore!, StringComparison.Ordinal)].Count(character => character == '\n'); builder.AppendLine(" public static async Task CompileAsync()") .AppendLine(" {") - .AppendLine($"#line {statementLine} \"{snippet.SourcePath}\""); + .AppendLine($"#line {splitStatementLine} \"{snippet.SourcePath}\""); foreach (var line in statementSource.Split('\n')) { builder.Append(" ").AppendLine(line); From 8190c64b98166614a35d9afd5ca8d672c477f0f3 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 21 Aug 2026 15:10:06 +0100 Subject: [PATCH 5/5] fix(docs): compile valid AOT examples --- docs/docs/writing-tests/aot.md | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/docs/docs/writing-tests/aot.md b/docs/docs/writing-tests/aot.md index 8be188391b2..e14d1de98f7 100644 --- a/docs/docs/writing-tests/aot.md +++ b/docs/docs/writing-tests/aot.md @@ -1,5 +1,3 @@ - - # AOT Compatibility and Generic Tests TUnit's source generation mode provides compile-time safety and performance benefits, but requires specific patterns for advanced scenarios like generic tests and complex data sources. @@ -29,8 +27,8 @@ public class GenericTests var value1 = default(T1); var value2 = default(T2); - await Assert.That(value1).IsNotNull().Or.IsEqualTo(default(T1)); - await Assert.That(value2).IsNotNull().Or.IsEqualTo(default(T2)); + await Assert.That(value1).IsEqualTo(default(T1)); + await Assert.That(value2).IsEqualTo(default(T2)); } } ``` @@ -54,16 +52,7 @@ public class GenericTestClass { var defaultValue = default(T); - // For reference types, default should be null - // For value types, default should be the type's default value - if (typeof(T).IsValueType) - { - await Assert.That(defaultValue).IsNotNull(); - } - else - { - await Assert.That(defaultValue).IsNull(); - } + await Assert.That(defaultValue).IsEqualTo(default(T)); } [Test] @@ -290,6 +279,7 @@ public async Task GenericTest() ### Data Source Diagnostics + ```csharp public class DataSourceDiagnostics {