Skip to content
Back to search

TUnit

A modern, fast and flexible .NET testing framework

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/thomhurst/TUnit with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/thomhurst/TUnit'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/thomhurst--tunit/badge.svg)](/listings/thomhurst--tunit)

HTML

<a href="/listings/thomhurst--tunit"><img src="/api/listings/thomhurst--tunit/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Using the Project Template (Recommended)

dotnet new install TUnit.Templates
dotnet new TUnit -n "MyTestProject"
cd MyTestProject
dotnet run

Manual Installation

dotnet add package TUnit

[Getting Started Guide](https://tunit.dev/docs/getting-started/installation) · [Migration Guides](https://tunit.dev/docs/migration/xunit)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 368 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ![TUnit](assets/banner.png)
  2. # TUnit
  3. 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).
  4. <div align="center">
  5. [![thomhurst%2FTUnit | Trendshift](https://trendshift.io/api/badge/repositories/11781)](https://trendshift.io/repositories/11781)
  6. ![GitHub Repo stars](https://img.shields.io/github/stars/thomhurst/TUnit) ![GitHub Issues or Pull Requests](https://img.shields.io/github/issues-closed-raw/thomhurst/TUnit)
  7. [![GitHub Sponsors](https://img.shields.io/github/sponsors/thomhurst)](https://github.com/sponsors/thomhurst) [![nuget](https://img.shields.io/nuget/v/TUnit.svg)](https://www.nuget.org/packages/TUnit/) [![NuGet Downloads](https://img.shields.io/nuget/dt/TUnit)](https://www.nuget.org/packages/TUnit/) ![GitHub Workflow Status (with event)](https://img.shields.io/github/actions/workflow/status/thomhurst/TUnit/dotnet.yml) ![GitHub last commit (branch)](https://img.shields.io/github/last-commit/thomhurst/TUnit/main) ![License](https://img.shields.io/github/license/thomhurst/TUnit)
  8. </div>
  9. ## What it looks like
  10. ```csharp
  11. [Test]
  12. [Arguments("GOLD", 100.00, 80.00)]
  13. [Arguments("SILVER", 100.00, 90.00)]
  14. public async Task Discount_Is_Applied(string tier, double subtotal, double expected)
  15. {
  16. var checkout = new CheckoutService();
  17. var total = await checkout.ApplyDiscountAsync(tier, subtotal);
  18. await Assert.That(total).IsEqualTo(expected);
  19. }
  20. ```
  21. If using TUnit Assertions, when a test fails, TUnit tells you what happened — including the actual expression you wrote:
  22. ```
  23. Expected to be 80
  24. but found 100
  25. at Assert.That(total).IsEqualTo(expected)
  26. ```
  27. Comparing objects? Instead of dumping two object graphs at you, TUnit pinpoints the difference:
  28. ```
  29. Expected to be equal to Employee { FirstName = "Victoria", LastName = "Apanii", Age = 30 }
  30. but differs at member FirstName: expected "Victoria" but found "ictoria"
  31. at Assert.That(actualEmployee).IsEqualTo(expectedEmployee)
  32. ```
  33. ## Why TUnit?
  34. - **Compile-time test discovery** — tests are wired up by a source generator at build time, not found via reflection at runtime. Faster startup, better IDE integration, and full Native AOT / trimming support.
  35. - **Compile-time safety** — a suite of Roslyn analyzers ships in the box, so mistakes like invalid hook signatures, broken data sources, and misused assertions fail your *build*, not your CI run.
  36. - **Parallel by default, with real control** — tests run concurrently out of the box; `[DependsOn]`, `[NotInParallel]`, and `[ParallelLimiter<T>]` give you precise ordering and throttling when you need it.
  37. - **Batteries included** — rich async assertions, shared fixtures with dependency injection, lifecycle hooks at every scope, and a source-generated mocking library — with first-class integrations for ASP.NET Core, Aspire, and Playwright.
  38. ## Performance
  39. Source generation shifts work from run time to build time: you pay a little up front at build, and every test run after that starts faster — dramatically so under Native AOT. The same test suites, run on every framework:
  40. <!-- benchmarks:start -->
  41. | Scenario | TUnit (AOT) | xUnit v3 (AOT) | TUnit | xUnit v3 | NUnit | MSTest |
  42. |----------|---|---|---|---|---|---|
  43. | Data-driven tests | 14.25 ms | 17.24 ms | 299.49 ms | 443.57 ms | 405.36 ms | 307.09 ms |
  44. | Async-heavy tests | 115.9 ms | 121.2 ms | 399.5 ms | 535.1 ms | 571.3 ms | 490.7 ms |
  45. | Matrix combinations | 168.3 ms | 280.5 ms | 505.0 ms | 809.5 ms | 1,498.9 ms | 1,413.0 ms |
  46. | Large suites (scale) | 13.43 ms | 20.26 ms | 312.49 ms | 455.93 ms | 431.81 ms | 320.07 ms |
  47. | Massive parallelism | 367.2 ms | 672.5 ms | 676.6 ms | 1,126.3 ms | 1,092.8 ms | 2,808.9 ms |
  48. | Setup/teardown lifecycle | 97.65 ms | 174.69 ms | 394.82 ms | 606.14 ms | 1,014.65 ms | 905.35 ms |
  49. <sub>Mean wall-clock time to run the same test suite. TUnit (AOT) 1.85.0 · xUnit v3 (AOT) 4.0.3 · TUnit 1.85.0 · xUnit v3 4.0.3 · NUnit 5.0.0 · MSTest 4.5.3. .NET SDK 11.0.100, .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4. Updated 2026-11-15 — regenerated weekly by the [Speed Comparison workflow](https://github.com/thomhurst/TUnit/actions/workflows/speed-comparison.yml). Full results and methodology: [tunit.dev/docs/benchmarks](https://tunit.dev/docs/benchmarks/).</sub>
  50. <!-- benchmarks:end -->
  51. ## Getting Started
  52. ### Using the Project Template (Recommended)
  53. ```bash
  54. dotnet new install TUnit.Templates
  55. dotnet new TUnit -n "MyTestProject"
  56. cd MyTestProject
  57. dotnet run
  58. ```
  59. ### Manual Installation
  60. ```bash
  61. dotnet add package TUnit
  62. ```
  63. [Getting Started Guide](https://tunit.dev/docs/getting-started/installation) · [Migration Guides](https://tunit.dev/docs/migration/xunit)
  64. ## A tour of the good parts
  65. ### Data-driven tests
  66. ```csharp
  67. [Test]
  68. [Arguments("user1@test.com", "ValidPassword123")]
  69. [Arguments("admin@test.com", "AdminPass789")]
  70. public async Task User_Login_Succeeds(string email, string password) { ... }
  71. // Matrix — generates a test for every combination (9 total here)
  72. [Test]
  73. [MatrixDataSource]
  74. public async Task Database_Operations_Work(
  75. [Matrix("Create", "Update", "Delete")] string operation,
  76. [Matrix("User", "Product", "Order")] string entity) { ... }
  77. ```
  78. Need more? `[MethodDataSource]` pulls rows from a method, and custom `DataSourceGenerator<T>` attributes let you build your own sources.
  79. ### Assertions that explain themselves
  80. Assertions are async, chainable, and produce the focused failure messages shown above:
  81. ```csharp
  82. await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK)
  83. .Because("the health endpoint should always be up");
  84. await Assert.That(order.Items)
  85. .Count().IsEqualTo(3)
  86. .And.Contains(item => item.Sku == "ABC-123");
  87. ```
  88. Defining your own assertion is one attribute on a plain method — TUnit generates the fluent extension for you:
  89. <!-- doc-test-member: split-before=// Now available -->
  90. ```csharp
  91. [GenerateAssertion]
  92. public static bool IsPositive(this int value) => value > 0;
  93. // Now available on Assert.That:
  94. var account = new { Balance = 1 };
  95. await Assert.That(account.Balance).IsPositive();
  96. ```
  97. ### Shared fixtures without the ceremony
  98. Inject anything into your test classes with `[ClassDataSource<T>]`. Implement `IAsyncInitializer` for async setup, `IAsyncDisposable` for teardown, and pick a sharing scope — `None`, `PerClass`, `PerAssembly`, `PerTestSession`, or `Keyed`:
  99. ```csharp
  100. public class PostgresContainer : IAsyncInitializer, IAsyncDisposable
  101. {
  102. public Task InitializeAsync() => Task.CompletedTask; // start container
  103. public ValueTask DisposeAsync() => ValueTask.CompletedTask; // stop container
  104. }
  105. public class OrderRepositoryTests
  106. {
  107. [ClassDataSource<PostgresContainer>(Shared = SharedType.PerTestSession)]
  108. public required PostgresContainer Postgres { get; init; }
  109. [Test]
  110. public async Task Saves_Order() { /* Postgres is initialized and shared across the whole run */ }
  111. }
  112. ```
  113. Property injection keeps base test classes clean — subclasses inherit the fixture without re-threading constructor parameters. Prefer a constructor parameter on the test class? That works too. Types created by `ClassDataSource<T>` require a public parameterless constructor; use property injection for their nested dependencies. Disposal is reference-counted, so shared fixtures are torn down exactly when the last test using them finishes.
  114. ### Parallelism you control
  115. Everything runs in parallel by default. Opt out or sequence tests where it matters:
  116. ```csharp
  117. [Test]
  118. public async Task Register_User() { ... }
  119. [Test, DependsOn(nameof(Register_User))]
  120. [Retry(3)]
  121. public async Task Login_With_Registered_User() { ... } // runs after Register_User passes
  122. [Test, NotInParallel("checkout-db")] // tests sharing a key never overlap
  123. public async Task Migrates_Schema() { ... }
  124. ```
  125. `[Repeat(n)]`, `[Timeout(ms)]`, and `[ParallelLimiter<T>]` round out the set.
  126. ### Lifecycle hooks at every scope
  127. ```csharp
  128. [Before(Test)] // also: Class, Assembly, TestSession
  129. public async Task SetUp() { ... }
  130. [After(Class)]
  131. public static async Task TearDownDatabase(ClassHookContext context) { ... }
  132. ```
  133. ### Mocking built in
  134. `TUnit.Mocks` is a source-generated, Native AOT-compatible mocking library — no runtime proxies, no `Castle.Core`. It works with any test framework:
  135. ```csharp
  136. var gateway = IPaymentGateway.Mock();
  137. gateway.ChargeAsync(Any<decimal>()).Returns(new ChargeResult(Success: true));
  138. var checkout = new CheckoutService(gateway.Object);
  139. var cart = new Cart(99.99m);
  140. await checkout.CompleteAsync(cart);
  141. gateway.ChargeAsync(99.99m).WasCalled(Times.Once);
  142. ```
  143. Companion packages mock the annoying stuff for you:
  144. ```csharp
  145. // TUnit.Mocks.Http — a real HttpClient backed by a scriptable handler
  146. using var client = Mock.HttpClient("https://api.example.com");
  147. client.Handler.OnGet("/users/1").RespondWithJson("""{ "id": 1 }""");
  148. // TUnit.Mocks.Logging — capture and verify ILogger output
  149. var logger = Mock.Logger<CheckoutService>();
  150. logger.VerifyLog().AtLevel(Microsoft.Extensions.Logging.LogLevel.Warning).ContainingMessage("retrying").WasCalled(Times.Once);
  151. ```
  152. ### Custom attributes
  153. Extend built-in base classes to create your own skip conditions, retry logic, and more:
  154. ```csharp
  155. public class WindowsOnlyAttribute : SkipAttribute
  156. {
  157. public WindowsOnlyAttribute() : base("Windows only") { }
  158. public override Task<bool> ShouldSkip(TestRegisteredContext testContext)
  159. => Task.FromResult(!OperatingSystem.IsWindows());
  160. }
  161. [Test, WindowsOnly]
  162. public async Task Windows_Specific_Feature() { ... }
  163. ```
  164. ## Integrations
  165. ### ASP.NET Core
  166. ```csharp
  167. public class ApiFactory : TestWebApplicationFactory<Program>;
  168. [ClassDataSource<ApiFactory>(Shared = SharedType.PerTestSession)]
  169. public class HealthCheckTests(ApiFactory factory)
  170. {
  171. [Test]
  172. public async Task Health_Endpoint_Responds()
  173. {
  174. using var client = factory.CreateClient();
  175. var response = await client.GetAsync("/health");
  176. await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
  177. }
  178. }
  179. ```
  180. ### Aspire
  181. Spin up your whole distributed app once per test session, with resource log forwarding and OpenTelemetry capture built in:
  182. ```csharp
  183. public class AppFixture : AspireFixture<Projects.MyApp_AppHost>;
  184. [ClassDataSource<AppFixture>(Shared = SharedType.PerTestSession)]
  185. public class ApiServiceTests(AppFixture app)
  186. {
  187. [Test]
  188. public async Task Api_Returns_Data()
  189. {
  190. var client = app.CreateHttpClient("apiservice");
  191. var response = await client.GetAsync("/weather");
  192. await Assert.That(response.IsSuccessStatusCode).IsTrue();
  193. }
  194. }
  195. ```
  196. ### Playwright
  197. Inherit from `PageTest` and a browser page is waiting for you — lifecycle fully managed:
  198. ```csharp
  199. public class HomePageTests : PageTest
  200. {
  201. [Test]
  202. public async Task Homepage_Loads()
  203. {
  204. await Page.GotoAsync("https://example.com");
  205. await Assert.That(await Page.TitleAsync()).Contains("Example");
  206. }
  207. }
  208. ```
  209. ### Property-based testing (FsCheck)
  210. ```csharp
  211. [Test, FsCheckProperty]
  212. public bool Reversing_Twice_Returns_Original(int[] array) =>
  213. array.SequenceEqual(array.AsEnumerable().Reverse().Reverse());
  214. ```
  215. ## More than C#
  216. TUnit runs F# and VB.NET test projects too, and `TUnit.Assertions.FSharp` provides idiomatic F# assertion helpers.
  217. ## IDE Support
  218. | IDE | Notes |
  219. |-----|-------|
  220. | **Visual Studio 2022 (17.13+)** | Works out of the box |
  221. | **Visual Studio 2022 (earlier)** | Enable "Use testing platform server mode" in Tools > Manage Preview Features |
  222. | **JetBrains Rider** | Enable "Testing Platform support" in Settings > Build, Execution, Deployment > Unit Testing > Testing Platform |
  223. | **VS Code** | Install [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) and enable "Use Testing Platform Protocol" |
  224. | **CLI** | Works with `dotnet test`, `dotnet run`, and direct execution |
  225. ## Packages
  226. | Package | Purpose |
  227. |---------|---------|
  228. | `TUnit` | Start here — the full framework (Core + Engine + Assertions) |
  229. | `TUnit.Core` | Shared test library components without an execution engine |
  230. | `TUnit.Engine` | Execution engine for test projects |
  231. | `TUnit.Assertions` | Standalone assertions — works with other test frameworks too |
  232. | `TUnit.Assertions.Should` | Optional FluentAssertions-style `value.Should().BeEqualTo(...)` syntax over `TUnit.Assertions` (beta) |
  233. | `TUnit.Mocks` | Source-generated, AOT-compatible mocking — works with any test runner |
  234. | `TUnit.Mocks.Http` | `HttpClient` mocking helpers built on `TUnit.Mocks` |
  235. | `TUnit.Mocks.Logging` | `ILogger` capture/verification helpers built on `TUnit.Mocks` |
  236. | `TUnit.AspNetCore` | ASP.NET Core integration — `WebApplicationFactory`-based test fixtures |
  237. | `TUnit.Aspire` | Aspire integration — distributed app host fixtures with OpenTelemetry capture |
  238. | `TUnit.Playwright` | Playwright integration with automatic browser lifecycle management |
  239. | `TUnit.FsCheck` | Property-based testing via FsCheck |
  240. | `TUnit.OpenTelemetry` | OpenTelemetry instrumentation for test runs |
  241. ## Migrating from xUnit, NUnit, or MSTest?
  242. The syntax will feel familiar. For example, xUnit's `[Fact]` becomes `[Test]`, and `[Theory]` + `[InlineData]` becomes `[Test]` + `[Arguments]`. See the migration guides for full details: [xUnit](https://tunit.dev/docs/migration/xunit) · [NUnit](https://tunit.dev/docs/migration/nunit) · [MSTest](https://tunit.dev/docs/migration/mstest).
  243. ## Install the agent skill
  244. Install the [TUnit agent skill](skills/tunit/SKILL.md) to help your coding agent write, migrate, and troubleshoot TUnit tests. It fetches only the relevant Markdown pages from [tunit.dev](https://tunit.dev), so detailed API guidance and examples stay up to date without loading the entire documentation into your agent's context. Network access is required to fetch those pages.
  245. With a GitHub CLI version that supports [`gh skill`](https://cli.github.com/manual/gh_skill), preview the skill and install it:
  246. ```sh
  247. gh skill preview thomhurst/TUnit tunit
  248. gh skill install thomhurst/TUnit tunit
  249. ```
  250. Use `--agent` and `--scope` to choose the installation target. Installation defaults to the latest release; until a release includes the skill, append `@main` to `tunit` in both commands to use the default branch. See the [installation options](https://cli.github.com/manual/gh_skill_install).
  251. ## Repository layout
  252. - `src/` — product libraries, analyzers, source generators, integrations, templates, and tools shipped as packages
  253. - `tests/` — unit, integration, snapshot, fixture, and cross-language test projects
  254. - `benchmarks/` — BenchmarkDotNet and profiling workloads
  255. - `examples/` — sample applications and test projects
  256. - `tools/` — repository automation and development utilities
  257. - `eng/` — shared MSBuild imports, signing key, and engineering assets
  258. - `scripts/` — local build, test, and profiling entry points
  259. Solutions and repository-wide SDK, package, and build configuration remain at root.
  260. ## Community
  261. - [Documentation](https://tunit.dev) — guides, tutorials, and API reference
  262. - [GitHub Discussions](https://github.com/thomhurst/TUnit/discussions) — questions and ideas welcome
  263. - [Issues](https://github.com/thomhurst/TUnit/issues) — bug reports and feature requests
  264. - [Changelog](https://github.com/thomhurst/TUnit/releases)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.