[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79XNP10P3MA8RAKA7DV211V":3,"skill-same:01M79XNP10P3MA8RAKA7DV211V":53},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M79XNP10P3MA8RAKA7DV211V","deniz-dotnet-general.writing-tunit-tests",null,"Write tests in TUnit — the attributes, the async assertion model, data-driven cases, lifecycle hooks, and the parallelism rules. USE FOR writing or fixing a test in a TUnit project, translating a test idea into TUnit syntax, or reviewing TUnit test code for API mistakes. DO NOT USE FOR deciding what to test, judging whether a test is any good, or running tests.","Blind-Striker\u002Fagent-skills-and-plugins","Blind-Striker","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1965259?v=4","01M79WFXTE5PH0C1VB7B54ANMN","Deniz İrgin","01M79WFXV5KZ5GST1K8G035DM5",1,"MIT","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fopencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.writing-tunit-tests\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: deniz-dotnet-general.writing-tunit-tests\ndescription: Write tests in TUnit — the attributes, the async assertion model,\n  data-driven cases, lifecycle hooks, and the parallelism rules. USE FOR writing\n  or fixing a test in a TUnit project, translating a test idea into TUnit\n  syntax, or reviewing TUnit test code for API mistakes. DO NOT USE FOR deciding\n  what to test, judging whether a test is any good, or running tests.\n---\n\n# Writing TUnit Tests\n\nTUnit is a .NET test framework built on Microsoft.Testing.Platform with compile-time test discovery.\nAlmost everything about it that surprises people comes from two design choices: **assertions are\nasync**, and **every test gets its own instance and runs in parallel with every other test**. Get\nthose two right and the rest is ordinary.\n\nThis skill is the syntax and the semantics. When a test's oracle depends on time, concurrency, a\nprocess boundary, or a mutant, read [references\u002Foracle-rules.md](references\u002Foracle-rules.md) as well.\nIt does not cover:\n\n- **what to test, and in what order** — that is the red-green loop in `deniz-process.test-driven-development`\n- **whether a test is worth having** — `deniz-dotnet-general.test-gap-analysis` asks whether a test would catch a\n  real bug, `deniz-dotnet-general.test-anti-patterns` catches the smells\n- **running or filtering tests** — `deniz-dotnet-general.run-tests` gives the exact command,\n  `deniz-dotnet-general.filter-syntax` the filter\n- **making untestable code testable** — that is a seam problem, and the ceremony that builds the\n  abstraction is one the human starts by name: `@deniz-dotnet-general.generate-testability-wrappers`\n\n## Setting up a project\n\nThe template is the shortest path, and it needs installing first:\n\n```bash\ndotnet new install TUnit.Templates\ndotnet new TUnit -n MyProject.Tests\n```\n\nBy hand, the test project is a **console executable**, not a library:\n\n```bash\ndotnet new console -n MyProject.Tests\ncd MyProject.Tests\ndotnet add package TUnit\n```\n\nThen delete the generated `Program.cs` and make sure the project keeps\n`\u003COutputType>Exe\u003C\u002FOutputType>`. The `TUnit` meta-package pulls in the assertions, the engine, the\nanalyzers and coverage support.\n\nThree things break discovery, and all three are things a .NET developer adds out of habit:\n\n- **`Microsoft.NET.Test.Sdk`** — remove it. It is VSTest infrastructure and TUnit is not VSTest.\n- **`coverlet.collector` \u002F `coverlet.msbuild`** — remove them for the same reason. Coverage comes\n  from `Microsoft.Testing.Extensions.CodeCoverage`, already in the meta-package, via `--coverage`.\n- **A missing `\u003COutputType>Exe\u003C\u002FOutputType>`** — without it nothing is discovered at all.\n\nThe sample project targets `net8.0`. TUnit also ships a `netstandard2.0` target, so .NET Framework\nworks, but it needs a polyfill package for types the old BCL lacks (`ModuleInitializerAttribute`\namong them).\n\n## The shape of a test\n\n```csharp\npublic class CheckoutTests\n{\n    [Test]\n    public async Task Discount_is_applied_to_a_gold_tier_subtotal()\n    {\n        var checkout = new CheckoutService();\n\n        var total = await checkout.ApplyDiscountAsync(\"GOLD\", 100.00);\n\n        await Assert.That(total).IsEqualTo(80.00);\n    }\n}\n```\n\n`[Test]` on the method, and nothing on the class — there is no `[TestClass]` or `[TestFixture]`.\nTest methods must be **public instance methods**. The bundled analyzers reject private or static\ntests, and generated invocations can produce ordinary C# compiler errors too — fix the build rather\nthan looking for a silently missing test.\n\nA test with no assertion passes as long as it does not throw. That is occasionally what you want (a\nsmoke test that a pipeline runs at all), but state it deliberately rather than by accident.\n\n## Assertions: everything is awaited\n\nThis is the rule that catches everyone:\n\n```csharp\nawait Assert.That(result).IsEqualTo(3);\n```\n\n`Assert.That(result).IsEqualTo(3)` **without `await` does nothing at runtime**. The fluent chain only\nbuilds a rule; `await` is what executes it. In a normal TUnit project the bundled analyzer makes a\nforgotten `await` a build error. If that analyzer is removed, suppressed, or demoted, the test can\ninstead pass silently whatever the value was.\n\nTwo things save you. The design reason: because every assertion is async, you never have to\nremember which ones need awaiting — they all do. And the mechanical backstop: the bundled analyzer\nraises **`TUnitAssertions0002`** (\"Assert statements must be awaited\") with a code fix. If you see\nthat ID in build output, that is what it means.\n\nThe catalogue, by what you are asserting:\n\n| Asserting | Written as |\n|---|---|\n| Equality | `IsEqualTo(x)` \u002F `IsNotEqualTo(x)` |\n| Same instance | `IsSameReferenceAs(x)` \u002F `IsNotSameReferenceAs(x)` |\n| Booleans | `IsTrue()` \u002F `IsFalse()` |\n| Numbers | `IsGreaterThan(x)`, `IsLessThan(x)`, `IsEqualTo(x).Within(0.001)` |\n| Collections | `Contains(item)` \u002F `DoesNotContain(item)`, predicate overloads too |\n| Strings | `Contains`, `StartsWith`, `EndsWith`, `Matches(pattern)` |\n| Exceptions | `Throws\u003CT>()`, `ThrowsExactly\u003CT>()`, `ThrowsNothing()` |\n\nPrefer the specific assertion over a boolean: `Assert.That(count).IsGreaterThan(0)` reports what it\nactually saw, while `Assert.That(count > 0).IsTrue()` can only tell you `false`.\n\nNumeric tolerance has to match the type — `Within(0.01f)` for a `float`, `Within(0.01m)` for a\n`decimal`.\n\nString assertions take modifiers: `.IgnoringCase()`, `.IgnoringWhitespace()`, `.WithTrimming()`,\n`.WithComparison(StringComparison.Ordinal)`.\n\n### Exceptions\n\nThe fluent form wraps a delegate, and it is the same `Throws\u003CT>()` whether the delegate is sync or\nasync:\n\n```csharp\nawait Assert.That(() => service.Parse(\"nonsense\")).Throws\u003CFormatException>();\nawait Assert.That(async () => await service.LoadAsync(id)).Throws\u003CHttpRequestException>();\n```\n\nThere is **no fluent `.ThrowsAsync\u003CT>()`**. There is a static helper of that name which returns the\nexception when you want to assert on its contents:\n\n```csharp\nvar ex = await Assert.ThrowsAsync\u003CValidationException>(async () => await service.SaveAsync(bad));\nawait Assert.That(ex.Message).Contains(\"email\");\n```\n\n### Combining\n\n`.And` and `.Or` both chain — but **never in the same chain**. Mixing them throws\n`MixedAndOrAssertionsException` at runtime, and the analyzer `TUnitAssertions0001` flags it first.\nSplit into two awaited assertions instead.\n\n## Data-driven tests\n\nInline rows:\n\n```csharp\n[Test]\n[Arguments(\"GOLD\", 100.00, 80.00)]\n[Arguments(\"SILVER\", 100.00, 90.00)]\n[Arguments(\"NONE\", 100.00, 100.00)]\npublic async Task Discount_matches_the_tier(string tier, double subtotal, double expected)\n{\n    var total = await new CheckoutService().ApplyDiscountAsync(tier, subtotal);\n    await Assert.That(total).IsEqualTo(expected);\n}\n```\n\nRows from a method use **`[MethodDataSource]`**. A static source is the simplest form:\n\n```csharp\n[Test]\n[MethodDataSource(nameof(DiscountCases))]\npublic async Task Discount_matches_the_tier(string tier, double subtotal, double expected) { }\n\npublic static IEnumerable\u003C(string tier, double subtotal, double expected)> DiscountCases() =>\n[\n    (\"GOLD\", 100.00, 80.00),\n    (\"SILVER\", 100.00, 90.00),\n];\n```\n\nPrefer the tuple because it keeps rows strongly typed. TUnit also accepts `IEnumerable\u003Cobject[]>`,\nbut then the compiler cannot check each element against the matching test parameter.\n`[MethodDataSource(typeof(Other), nameof(Other.Cases))]` reaches another class, and\n`[MethodDataSource\u003CT>(nameof(T.Cases))]` names a provider without reflection. Public instance\nsources are supported when TUnit can construct the test or provider instance;\n`[InstanceMethodDataSource]` makes that lifetime choice explicit.\n\n**`[ClassDataSource\u003CT>]` is not a row provider.** Despite the name it is the shared-fixture\nmechanism — the equivalent of xUnit's `IClassFixture\u003CT>`. It injects one managed instance whose\nlifetime you choose:\n\n```csharp\n[ClassDataSource\u003CDatabaseFixture>(Shared = SharedType.PerClass)]\npublic class OrderRepositoryTests(DatabaseFixture db) { }\n```\n\n`SharedType` is `None`, `PerClass`, `PerAssembly`, `PerTestSession`, or `Keyed` (with `Key`). If you\nactually want rows from a class, use `[MethodDataSource(nameof(MyClass.Rows))]`.\n\nFor a generated source, subclass `DataSourceGeneratorAttribute\u003CT…>` (or the async \u002F untyped\nvariants) and override `GenerateDataSources(DataGeneratorMetadata)`. It returns `Func\u003C…>` delegates,\nnot values. There is no `ITestDataSource` — that is an MSTest interface and it does not exist here.\n\nAlso available: `[MatrixDataSource]` with `[Matrix(...)]` per parameter for a cross product, and\n`[GenerateGenericTest(typeof(...))]` for generic test methods. `TestDataRow\u003CT>` is not an attribute;\nreturn that wrapper from a data-source method when a row needs metadata such as a custom display\nname or categories.\n\n## Parallelism, and the instance rule that goes with it\n\n**Every test is eligible to run concurrently with every other test — including the ones in the same\nclass.** There is no implicit per-class serialisation. If you are coming from xUnit, this is the\nassumption to drop: xUnit collections serialise a class, TUnit does not.\n\nPaired with that: **a fresh instance of the test class is created for every test method.**\n\nTogether those two make instance fields useless as a channel between tests, and the failure is\nquiet:\n\n```csharp\npublic class Wrong\n{\n    private int _value;                          \u002F\u002F reset for every test\n\n    [Test]\n    public void Sets_it() => _value = 99;\n\n    [Test]\n    public async Task Reads_it()\n        => await Assert.That(_value).IsEqualTo(99);   \u002F\u002F fails: different instance, _value is 0\n}\n```\n\nShare deliberately instead — `static` for genuinely global state, `[ClassDataSource\u003CT>]` for a\nfixture with a managed lifetime.\n\nWhen a test genuinely cannot run beside others, say so:\n\n- `[NotInParallel]` — with optional constraint keys and an `Order`\n- `[ParallelGroup(\"name\")]` — everything in the group runs together, apart from other groups\n- `[ParallelLimiter\u003CT>]` — cap concurrency, where `T : IParallelLimit` has a parameterless\n  constructor and an `int Limit`. Mind the spelling: the attribute ends in **-er**, the interface\n  does not. Assembly-wide: `[assembly: ParallelLimiter\u003CMyLimit>]`\n\nOrdering is a dependency, not a number: `[DependsOn(nameof(OtherTest))]` makes this test wait for\nthat one while everything else keeps running. `ProceedOnFailure = true` runs it even if the\ndependency failed.\n\n## Lifecycle hooks\n\n`[Before(X)]` and `[After(X)]` where `X` is `Test`, `Class`, `Assembly`, `TestSession`, or\n`TestDiscovery`. They nest outermost to innermost — TestSession, Assembly, Class, Test — and the\n`After` side unwinds in reverse.\n\n**Staticness is not optional, and the bundled analyzers fail the build when it is wrong:**\n\n| Hook level | Must be |\n|---|---|\n| `Test` | instance |\n| `Class`, `Assembly`, `TestSession`, `TestDiscovery` | **static** |\n| every `[BeforeEvery(...)]` \u002F `[AfterEvery(...)]` | **static** |\n\n`[Before(Class)]` runs once for *this* class. `[BeforeEvery(Class)]` runs before *every* class in\nthe session — a different job, and the `Every` family is easy to miss.\n\nNever write `async void` on a hook; it is a compile error here.\n\nMultiple `[After(Test)]` methods all run even when one throws, and the exceptions are aggregated —\nso cleanup does not silently stop halfway.\n\n## Control attributes\n\n| Attribute | Effect |\n|---|---|\n| `[Repeat(n)]` | **`n` more runs, so `n + 1` total.** `[Repeat(3)]` executes four times |\n| `[Retry(n)]` | Re-run on exception. Subclass `RetryAttribute` and override `ShouldRetry` to be selective |\n| `[Skip(\"reason\")]` | Reason is required. Subclass for conditional skipping; `Skip.Test(reason)` skips at runtime, including from a `[Before(Test)]` hook |\n| `[Timeout(30_000)]` | **Milliseconds.** Take a `CancellationToken` parameter and pass it down, or the timeout cannot actually stop the work. Each retry gets a fresh one |\n| `[Category(\"Smoke\")]` | Groups tests for filtering |\n| `[Property(\"key\", \"value\")]` | Arbitrary metadata — the `[Trait]` equivalent |\n| `[DisplayName(\"Adds $a and $b\")]` | `$parameterName` interpolates the argument |\n\nScope depends on the attribute. Scoped controls such as repeat, retry, skip, and timeout resolve the\nmost specific applicable value. `Category` and `Property` are additive metadata across their\nsupported scopes, while `DisplayName` applies only to methods and classes.\n\n## Test output\n\nThere is no `ITestOutputHelper`. Ordinary test methods read the current context from\n`TestContext.Current!` — `TestContext` parameters are supported by test-level hooks, not injected\ninto `[Test]` methods:\n\n```csharp\n[Test]\npublic void Writes_a_note()\n{\n    var context = TestContext.Current!;\n    context.Output.WriteLine(\"about to call the API\");\n}\n```\n\n`Output.WriteError(...)` and `Output.AttachArtifact(...)` are there too.\n\n## Mocking\n\nTUnit ships a separate source-generated mocking package. Add it explicitly and use a C# 14-capable\nSDK\u002Fcompiler; the `TUnit` meta-package alone does not include it:\n\n```bash\ndotnet add package TUnit.Mocks\n```\n\nIt works under Native AOT where reflection-based mockers do not:\n\n```csharp\nvar mock = IGreeter.Mock();\nmock.Greet(Any()).Returns(\"Hello!\");\n\nIGreeter greeter = mock;\nvar result = greeter.Greet(\"Alice\");\n\nmock.Greet(\"Alice\").WasCalled(Times.Once);\n```\n\n`Mock.Of\u003CIGreeter>()` is the alternative entry point. `TUnit.Mocks.Http` and `TUnit.Mocks.Logging`\ncover those two cases specifically. Ordinary mocking libraries still work — they are just libraries\n— but they give up AOT compatibility.\n\n## Compile-time discovery, and what it forbids\n\nTests are found by a Roslyn source generator, not by reflection. That is what makes Native AOT and\nsingle-file publish work — and it is the reason a few things that compile in other frameworks do not\ncompile here.\n\n**Under Native AOT these are hard rules.** A reflection mode exists (`--reflection`,\n`[assembly: ReflectionMode]`, or `TUNIT_EXECUTION_MODE=reflection`) for cases the generator cannot\nsee, such as bUnit Razor components — but it is exactly the thing AOT removes, so an AOT-published\nsuite has no escape hatch. Write for the generator from the start.\n\nWhat the generator has to be able to see at compile time:\n\n- **Data-source members must be named at compile time.** Use `nameof`, not a value resolved at\n  runtime. Static sources are simplest; an instance source also works when TUnit can generate a\n  factory for a constructible test or provider instance.\n- **Generic test methods and classes need `[GenerateGenericTest(typeof(...))]`**, one per closed\n  type you want emitted. Without a concrete type the generator has no runnable test to produce.\n- **Do not diagnose those two cases from `TUnit0058` or `TUnit0059`.** In current TUnit,\n  `TUnit0058` reports unsupported hook parameters and `TUnit0059` reports an abstract data-driven\n  test class whose concrete subclass is missing `[InheritsTests]`.\n- **Mocking has to be generated too.** Reflection-based mockers cannot run under AOT, which is why\n  `TUnit.Mocks` is source-generated.\n\n## Coming from another framework\n\n| xUnit | TUnit |\n|---|---|\n| `[Fact]`, `[Theory]` | `[Test]` |\n| `[InlineData]` | `[Arguments]` |\n| `[MemberData(nameof(X))]` | `[MethodDataSource(nameof(X))]` |\n| `[ClassData(typeof(X))]` | `[MethodDataSource(nameof(X.Rows))]` |\n| `[Trait(\"k\",\"v\")]` | `[Property(\"k\",\"v\")]` |\n| `IClassFixture\u003CT>` | `[ClassDataSource\u003CT>(Shared = SharedType.PerClass)]` |\n| `ICollectionFixture\u003CT>` | `[ClassDataSource\u003CT>(Shared = SharedType.Keyed, Key = \"name\")]` |\n| `IAsyncLifetime` | `[Before(Test)]` \u002F `[After(Test)]` |\n| `ITestOutputHelper` | `TestContext.Output` |\n| constructor + `IDisposable` | `[Before(Test)]` \u002F `[After(Test)]` |\n\nFrom **NUnit**, the trap is the opposite of xUnit's: NUnit reuses one fixture instance across a\nclass, TUnit creates a fresh one per test.\n\nFrom **MSTest**, the trap is `ITestDataSource`, which does not exist here.\n","# Writing TUnit Tests\n\nTUnit is a .NET test framework built on Microsoft.Testing.Platform with compile-time test discovery.\nAlmost everything about it that surprises people comes from two design choices: **assertions are\nasync**, and **every test gets its own instance and runs in parallel with every other test**. Get\nthose two right and the rest is ordinary.\n\nThis skill is the syntax and the semantics. When a test's oracle depends on time, concurrency, a\nprocess boundary, or a mutant, read [references\u002Foracle-rules.md](references\u002Foracle-rules.md) as well.\nIt does not cover:\n\n- **what to test, and in what order** — that is the red-green loop in `deniz-process.test-driven-development`\n- **whether a test is worth having** — `deniz-dotnet-general.test-gap-analysis` asks whether a test would catch a\n  real bug, `deniz-dotnet-general.test-anti-patterns` catches the smells\n- **running or filtering tests** — `deniz-dotnet-general.run-tests` gives the exact command,\n  `deniz-dotnet-general.filter-syntax` the filter\n- **making untestable code testable** — that is a seam problem, and the ceremony that builds the\n  abstraction is one the human starts by name: `@deniz-dotnet-general.generate-testability-wrappers`\n\n## Setting up a project\n\nThe template is the shortest path, and it needs installing first:\n\n```bash\ndotnet new install TUnit.Templates\ndotnet new TUnit -n MyProject.Tests\n```\n\nBy hand, the test project is a **console executable**, not a library:\n\n```bash\ndotnet new console -n MyProject.Tests\ncd MyProject.Tests\ndotnet add package TUnit\n```\n\nThen delete the generated `Program.cs` and make sure the project keeps\n`\u003COutputType>Exe\u003C\u002FOutputType>`. The `TUnit` meta-package pulls in the assertions, the engine, the\nanalyzers and coverage support.\n\nThree things break discovery, and all three are things a .NET developer adds out of habit:\n\n- **`Microsoft.NET.Test.Sdk`** — remove it. It is VSTest infrastructure and TUnit is not VSTest.\n- **`coverlet.collector` \u002F `coverlet.msbuild`** — remove them for the same reason. Coverage comes\n  from `Microsoft.Testing.Extensions.CodeCoverage`, already in the meta-package, via `--coverage`.\n- **A missing `\u003COutputType>Exe\u003C\u002FOutputType>`** — without it nothing is discovered at all.\n\nThe sample project targets `net8.0`. TUnit also ships a `netstandard2.0` target, so .NET Framework\nworks, but it needs a polyfill package for types the old BCL lacks (`ModuleInitializerAttribute`\namong them).\n\n## The shape of a test\n\n```csharp\npublic class CheckoutTests\n{\n    [Test]\n    public async Task Discount_is_applied_to_a_gold_tier_subtotal()\n    {\n        var checkout = new CheckoutService();\n\n        var total = await checkout.ApplyDiscountAsync(\"GOLD\", 100.00);\n\n        await Assert.That(total).IsEqualTo(80.00);\n    }\n}\n```\n\n`[Test]` on the method, and nothing on the class — there is no `[TestClass]` or `[TestFixture]`.\nTest methods must be **public instance methods**. The bundled analyzers reject private or static\ntests, and generated invocations can produce ordinary C# compiler errors too — fix the build rather\nthan looking for a silently missing test.\n\nA test with no assertion passes as long as it does not throw. That is occasionally what you want (a\nsmoke test that a pipeline runs at all), but state it deliberately rather than by accident.\n\n## Assertions: everything is awaited\n\nThis is the rule that catches everyone:\n\n```csharp\nawait Assert.That(result).IsEqualTo(3);\n```\n\n`Assert.That(result).IsEqualTo(3)` **without `await` does nothing at runtime**. The fluent chain only\nbuilds a rule; `await` is what executes it. In a normal TUnit project the bundled analyzer makes a\nforgotten `await` a build error. If that analyzer is removed, suppressed, or demoted, the test can\ninstead pass silently whatever the value was.\n\nTwo things save you. The design reason: because every assertion is async, you never have to\nremember which ones need awaiting — they all do. And the mechanical backstop: the bundled analyzer\nraises **`TUnitAssertions0002`** (\"Assert statements must be awaited\") with a code fix. If you see\nthat ID in build output, that is what it means.\n\nThe catalogue, by what you are asserting:\n\n| Asserting | Written as |\n|---|---|\n| Equality | `IsEqualTo(x)` \u002F `IsNotEqualTo(x)` |\n| Same instance | `IsSameReferenceAs(x)` \u002F `IsNotSameReferenceAs(x)` |\n| Booleans | `IsTrue()` \u002F `IsFalse()` |\n| Numbers | `IsGreaterThan(x)`, `IsLessThan(x)`, `IsEqualTo(x).Within(0.001)` |\n| Collections | `Contains(item)` \u002F `DoesNotContain(item)`, predicate overloads too |\n| Strings | `Contains`, `StartsWith`, `EndsWith`, `Matches(pattern)` |\n| Exceptions | `Throws\u003CT>()`, `ThrowsExactly\u003CT>()`, `ThrowsNothing()` |\n\nPrefer the specific assertion over a boolean: `Assert.That(count).IsGreaterThan(0)` reports what it\nactually saw, while `Assert.That(count > 0).IsTrue()` can only tell you `false`.\n\nNumeric tolerance has to match the type — `Within(0.01f)` for a `float`, `Within(0.01m)` for a\n`decimal`.\n\nString assertions take modifiers: `.IgnoringCase()`, `.IgnoringWhitespace()`, `.WithTrimming()`,\n`.WithComparison(StringComparison.Ordinal)`.\n\n### Exceptions\n\nThe fluent form wraps a delegate, and it is the same `Throws\u003CT>()` whether the delegate is sync or\nasync:\n\n```csharp\nawait Assert.That(() => service.Parse(\"nonsense\")).Throws\u003CFormatException>();\nawait Assert.That(async () => await service.LoadAsync(id)).Throws\u003CHttpRequestException>();\n```\n\nThere is **no fluent `.ThrowsAsync\u003CT>()`**. There is a static helper of that name which returns the\nexception when you want to assert on its contents:\n\n```csharp\nvar ex = await Assert.ThrowsAsync\u003CValidationException>(async () => await service.SaveAsync(bad));\nawait Assert.That(ex.Message).Contains(\"email\");\n```\n\n### Combining\n\n`.And` and `.Or` both chain — but **never in the same chain**. Mixing them throws\n`MixedAndOrAssertionsException` at runtime, and the analyzer `TUnitAssertions0001` flags it first.\nSplit into two awaited assertions instead.\n\n## Data-driven tests\n\nInline rows:\n\n```csharp\n[Test]\n[Arguments(\"GOLD\", 100.00, 80.00)]\n[Arguments(\"SILVER\", 100.00, 90.00)]\n[Arguments(\"NONE\", 100.00, 100.00)]\npublic async Task Discount_matches_the_tier(string tier, double subtotal, double expected)\n{\n    var total = await new CheckoutService().ApplyDiscountAsync(tier, subtotal);\n    await Assert.That(total).IsEqualTo(expected);\n}\n```\n\nRows from a method use **`[MethodDataSource]`**. A static source is the simplest form:\n\n```csharp\n[Test]\n[MethodDataSource(nameof(DiscountCases))]\npublic async Task Discount_matches_the_tier(string tier, double subtotal, double expected) { }\n\npublic static IEnumerable\u003C(string tier, double subtotal, double expected)> DiscountCases() =>\n[\n    (\"GOLD\", 100.00, 80.00),\n    (\"SILVER\", 100.00, 90.00),\n];\n```\n\nPrefer the tuple because it keeps rows strongly typed. TUnit also accepts `IEnumerable\u003Cobject[]>`,\nbut then the compiler cannot check each element against the matching test parameter.\n`[MethodDataSource(typeof(Other), nameof(Other.Cases))]` reaches another class, and\n`[MethodDataSource\u003CT>(nameof(T.Cases))]` names a provider without reflection. Public instance\nsources are supported when TUnit can construct the test or provider instance;\n`[InstanceMethodDataSource]` makes that lifetime choice explicit.\n\n**`[ClassDataSource\u003CT>]` is not a row provider.** Despite the name it is the shared-fixture\nmechanism — the equivalent of xUnit's `IClassFixture\u003CT>`. It injects one managed instance whose\nlifetime you choose:\n\n```csharp\n[ClassDataSource\u003CDatabaseFixture>(Shared = SharedType.PerClass)]\npublic class OrderRepositoryTests(DatabaseFixture db) { }\n```\n\n`SharedType` is `None`, `PerClass`, `PerAssembly`, `PerTestSession`, or `Keyed` (with `Key`). If you\nactually want rows from a class, use `[MethodDataSource(nameof(MyClass.Rows))]`.\n\nFor a generated source, subclass `DataSourceGeneratorAttribute\u003CT…>` (or the async \u002F untyped\nvariants) and override `GenerateDataSources(DataGeneratorMetadata)`. It returns `Func\u003C…>` delegates,\nnot values. There is no `ITestDataSource` — that is an MSTest interface and it does not exist here.\n\nAlso available: `[MatrixDataSource]` with `[Matrix(...)]` per parameter for a cross product, and\n`[GenerateGenericTest(typeof(...))]` for generic test methods. `TestDataRow\u003CT>` is not an attribute;\nreturn that wrapper from a data-source method when a row needs metadata such as a custom display\nname or categories.\n\n## Parallelism, and the instance rule that goes with it\n\n**Every test is eligible to run concurrently with every other test — including the ones in the same\nclass.** There is no implicit per-class serialisation. If you are coming from xUnit, this is the\nassumption to drop: xUnit collections serialise a class, TUnit does not.\n\nPaired with that: **a fresh instance of the test class is created for every test method.**\n\nTogether those two make instance fields useless as a channel between tests, and the failure is\nquiet:\n\n```csharp\npublic class Wrong\n{\n    private int _value;                          \u002F\u002F reset for every test\n\n    [Test]\n    public void Sets_it() => _value = 99;\n\n    [Test]\n    public async Task Reads_it()\n        => await Assert.That(_value).IsEqualTo(99);   \u002F\u002F fails: different instance, _value is 0\n}\n```\n\nShare deliberately instead — `static` for genuinely global state, `[ClassDataSource\u003CT>]` for a\nfixture with a managed lifetime.\n\nWhen a test genuinely cannot run beside others, say so:\n\n- `[NotInParallel]` — with optional constraint keys and an `Order`\n- `[ParallelGroup(\"name\")]` — everything in the group runs together, apart from other groups\n- `[ParallelLimiter\u003CT>]` — cap concurrency, where `T : IParallelLimit` has a parameterless\n  constructor and an `int Limit`. Mind the spelling: the attribute ends in **-er**, the interface\n  does not. Assembly-wide: `[assembly: ParallelLimiter\u003CMyLimit>]`\n\nOrdering is a dependency, not a number: `[DependsOn(nameof(OtherTest))]` makes this test wait for\nthat one while everything else keeps running. `ProceedOnFailure = true` runs it even if the\ndependency failed.\n\n## Lifecycle hooks\n\n`[Before(X)]` and `[After(X)]` where `X` is `Test`, `Class`, `Assembly`, `TestSession`, or\n`TestDiscovery`. They nest outermost to innermost — TestSession, Assembly, Class, Test — and the\n`After` side unwinds in reverse.\n\n**Staticness is not optional, and the bundled analyzers fail the build when it is wrong:**\n\n| Hook level | Must be |\n|---|---|\n| `Test` | instance |\n| `Class`, `Assembly`, `TestSession`, `TestDiscovery` | **static** |\n| every `[BeforeEvery(...)]` \u002F `[AfterEvery(...)]` | **static** |\n\n`[Before(Class)]` runs once for *this* class. `[BeforeEvery(Class)]` runs before *every* class in\nthe session — a different job, and the `Every` family is easy to miss.\n\nNever write `async void` on a hook; it is a compile error here.\n\nMultiple `[After(Test)]` methods all run even when one throws, and the exceptions are aggregated —\nso cleanup does not silently stop halfway.\n\n## Control attributes\n\n| Attribute | Effect |\n|---|---|\n| `[Repeat(n)]` | **`n` more runs, so `n + 1` total.** `[Repeat(3)]` executes four times |\n| `[Retry(n)]` | Re-run on exception. Subclass `RetryAttribute` and override `ShouldRetry` to be selective |\n| `[Skip(\"reason\")]` | Reason is required. Subclass for conditional skipping; `Skip.Test(reason)` skips at runtime, including from a `[Before(Test)]` hook |\n| `[Timeout(30_000)]` | **Milliseconds.** Take a `CancellationToken` parameter and pass it down, or the timeout cannot actually stop the work. Each retry gets a fresh one |\n| `[Category(\"Smoke\")]` | Groups tests for filtering |\n| `[Property(\"key\", \"value\")]` | Arbitrary metadata — the `[Trait]` equivalent |\n| `[DisplayName(\"Adds $a and $b\")]` | `$parameterName` interpolates the argument |\n\nScope depends on the attribute. Scoped controls such as repeat, retry, skip, and timeout resolve the\nmost specific applicable value. `Category` and `Property` are additive metadata across their\nsupported scopes, while `DisplayName` applies only to methods and classes.\n\n## Test output\n\nThere is no `ITestOutputHelper`. Ordinary test methods read the current context from\n`TestContext.Current!` — `TestContext` parameters are supported by test-level hooks, not injected\ninto `[Test]` methods:\n\n```csharp\n[Test]\npublic void Writes_a_note()\n{\n    var context = TestContext.Current!;\n    context.Output.WriteLine(\"about to call the API\");\n}\n```\n\n`Output.WriteError(...)` and `Output.AttachArtifact(...)` are there too.\n\n## Mocking\n\nTUnit ships a separate source-generated mocking package. Add it explicitly and use a C# 14-capable\nSDK\u002Fcompiler; the `TUnit` meta-package alone does not include it:\n\n```bash\ndotnet add package TUnit.Mocks\n```\n\nIt works under Native AOT where reflection-based mockers do not:\n\n```csharp\nvar mock = IGreeter.Mock();\nmock.Greet(Any()).Returns(\"Hello!\");\n\nIGreeter greeter = mock;\nvar result = greeter.Greet(\"Alice\");\n\nmock.Greet(\"Alice\").WasCalled(Times.Once);\n```\n\n`Mock.Of\u003CIGreeter>()` is the alternative entry point. `TUnit.Mocks.Http` and `TUnit.Mocks.Logging`\ncover those two cases specifically. Ordinary mocking libraries still work — they are just libraries\n— but they give up AOT compatibility.\n\n## Compile-time discovery, and what it forbids\n\nTests are found by a Roslyn source generator, not by reflection. That is what makes Native AOT and\nsingle-file publish work — and it is the reason a few things that compile in other frameworks do not\ncompile here.\n\n**Under Native AOT these are hard rules.** A reflection mode exists (`--reflection`,\n`[assembly: ReflectionMode]`, or `TUNIT_EXECUTION_MODE=reflection`) for cases the generator cannot\nsee, such as bUnit Razor components — but it is exactly the thing AOT removes, so an AOT-published\nsuite has no escape hatch. Write for the generator from the start.\n\nWhat the generator has to be able to see at compile time:\n\n- **Data-source members must be named at compile time.** Use `nameof`, not a value resolved at\n  runtime. Static sources are simplest; an instance source also works when TUnit can generate a\n  factory for a constructible test or provider instance.\n- **Generic test methods and classes need `[GenerateGenericTest(typeof(...))]`**, one per closed\n  type you want emitted. Without a concrete type the generator has no runnable test to produce.\n- **Do not diagnose those two cases from `TUnit0058` or `TUnit0059`.** In current TUnit,\n  `TUnit0058` reports unsupported hook parameters and `TUnit0059` reports an abstract data-driven\n  test class whose concrete subclass is missing `[InheritsTests]`.\n- **Mocking has to be generated too.** Reflection-based mockers cannot run under AOT, which is why\n  `TUnit.Mocks` is source-generated.\n\n## Coming from another framework\n\n| xUnit | TUnit |\n|---|---|\n| `[Fact]`, `[Theory]` | `[Test]` |\n| `[InlineData]` | `[Arguments]` |\n| `[MemberData(nameof(X))]` | `[MethodDataSource(nameof(X))]` |\n| `[ClassData(typeof(X))]` | `[MethodDataSource(nameof(X.Rows))]` |\n| `[Trait(\"k\",\"v\")]` | `[Property(\"k\",\"v\")]` |\n| `IClassFixture\u003CT>` | `[ClassDataSource\u003CT>(Shared = SharedType.PerClass)]` |\n| `ICollectionFixture\u003CT>` | `[ClassDataSource\u003CT>(Shared = SharedType.Keyed, Key = \"name\")]` |\n| `IAsyncLifetime` | `[Before(Test)]` \u002F `[After(Test)]` |\n| `ITestOutputHelper` | `TestContext.Output` |\n| constructor + `IDisposable` | `[Before(Test)]` \u002F `[After(Test)]` |\n\nFrom **NUnit**, the trap is the opposite of xUnit's: NUnit reuses one fixture instance across a\nclass, TUnit creates a fresh one per test.\n\nFrom **MSTest**, the trap is `ITestDataSource`, which does not exist here.\n",{"name":5,"description":7},"master","b30b1c1908dbc56a8184128f18803053d762ccb5","opencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.writing-tunit-tests",0,"https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins","https:\u002F\u002Fgithub.com\u002FBlind-Striker","denizirgin.com","VP of Engineering - \r\n@armutcom @homeruntech @prontopro\r\n |  Speaker \r\n@CodeFiction\r\n, http:\u002F\u002Fcodefiction.tech | Developer, gamer, blogger, maiden iron fan","2026-11-13 00:23:18",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill deniz-dotnet-general.writing-tunit-tests",{"tool":39,"command":40},"bunx","bunx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill deniz-dotnet-general.writing-tunit-tests",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill deniz-dotnet-general.writing-tunit-tests","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fopencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.writing-tunit-tests\u002FSKILL.md",true,[47],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"references\u002Foracle-rules.md","REFERENCE","参考文档",2857,"https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fopencode\u002Fdeniz-dotnet-general\u002Fskills\u002Fdeniz-dotnet-general.writing-tunit-tests\u002Freferences\u002Foracle-rules.md",[54,60,67,74,81,88],{"skillNo":55,"name":56,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M79YGWBJ52PHMSTKJ3RJ3AWR","writing-tunit-tests","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fwriting-tunit-tests\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M79YGR3Y9RCRS6TD71D0KKP8","dotnet-walls","Walls for a .NET change in a repository without its own quality gates — pinned, ephemeral analyzer, format, clone and scanner commands for the verify step, their identity ratchet, and the build traps. Use during a walls preflight, or when a worker's verify step needs .NET quality gates.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fdotnet-walls\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M79YGFNJBST7D803NQW3SBYM","csharp-15","Write, review and modernize C# 15 (.NET 11) code correctly. Covers every C# 15 feature - collection expression arguments (`[with(...), ...]`), union types (`union`, `[Union]`, `IUnion`, custom unions), closed class hierarchies (`closed`), extension indexers, labeled `break`\u002F`continue`, non-virtual static interface members on runtimes without default interface methods, and the preview memory-safety model (`unsafe(expr)`, `safe`, requires-unsafe members). Use when code targets net11.0 or LangVersion 15\u002Fpreview, when the user mentions any of these features, when replacing marker interfaces, OneOf-style results, `goto`\u002Fflag loop exits or capacity\u002Fcomparer boilerplate, or when the build reports CS8121, CS8509, CS8655, CS8510, CS0121\u002FCS0411 on a `with(...)` element, CS9370, CS9380 or CS9363.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fcsharp-15\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M79YGAV031473HSX6FN87ENH","verified-waves","Run one task as verified multi-agent waves. Plans the fan-out, sends findings to fresh skeptics, keeps a ledger, and reports N of M done; small tasks stay solo.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fverified-waves\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M79YG6QXNND4WRPP3GATSY8J","harness","The bundled dispatch harness, which runs a task file on worker models through OpenCode or Codex, fences their writes, escalates their asks to the operator, settles each result from git and its verify commands, and records every step in a ledger. Its commands, task file, modes and write fence, configuration, runs and their recovery, ledger and exit codes.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fharness\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M79YG2P5S91SDTA5912XJ4FV","delegating-to-worker-models","Use when you hand off implementation, a plan, research a decision will rely on, or a review, and you brief the worker and check what comes back. A subagent that searches, reads in parallel, or keeps your context small is ordinary tool use. Covers what stays with you, the mechanism, assigning work by strength, the walls preflight, prompts without contradictions, the worker contract and model profiles, evidence from your own run, review, and the fix-up loop.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fdelegating-to-worker-models\u002FSKILL.md",[],[]]