Skip to content

thomhurst/TUnit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TUnit

thomhurst%2FTUnit | Trendshift

A modern, flexible and fast testing framework for .NET 8 and up. With Native AOT and Trimmed Single File application support included!

TUnit is designed to aid with all testing types:

  • Unit
  • Integration
  • Acceptance
  • and more!

GitHub Repo stars GitHub Sponsors nuget NuGet Downloads GitHub Workflow Status (with event) GitHub last commit (branch) License

Documentation

See here: https://thomhurst.github.io/TUnit/

Modern and Fast

TUnit leverages source generators to locate and register your tests as opposed to reflection. You'll have a slight bump in build time, but a speedier runtime.

TUnit also builds upon the newer Microsoft.Testing.Platform, whereas most other frameworks you'll have used will use VSTest. The new platform was reconstructed from the ground up to address pain points, be more extensible, and be faster.

Hooks, Events and Lifecycles

One of the most powerful parts of TUnit is the information you have available to you because of the source generation and the events you can subscribe to. Because tests are constructed at the point of discovery, and not at runtime, you know all your arguments, properties, etc. upfront.

You can then register to be notified about various events such as test registered (scheduled to run in this test session at some point in the future), test started, test finished, etc.

Say we injected an external object into our tests: By knowing how many tests are registered, we could count them up, and then on a test end event, we could decrease the count. When hitting 0, we know our object isn't going to be used by any other tests, so we can dispose of it. We know when we can handle the lifecycle, and this prevents it from living till the end of the test session where it could be hanging on to precious resources.

Built in Analyzers

TUnit tries to help you write your tests correctly with analyzers. If something isn't quite right, an analyzer should tell you what's wrong.

IDE

TUnit is built on top of the newer Microsoft.Testing.Platform, as opposed to the older VSTest platform. Because the infrastructure behind the scenes is new and different, you may need to enable some settings. This should just be a one time thing.

Visual Studio

Visual Studio is supported. The "Use testing platform server mode" option must be selected in Tools > Manage Preview Features.

Rider

Rider is supported. The Enable Testing Platform support option must be selected in Settings > Build, Execution, Deployment > Unit Testing > VSTest.

VS Code

Visual Studio Code is supported.

  • Install the extension Name: C# Dev Kit
  • Go to the C# Dev Kit extension's settings
  • Enable Dotnet > Test Window > Use Testing Platform Protocol

CLI

dotnet CLI - Fully supported. Tests should be runnable with dotnet test, dotnet run, dotnet exec or executing an executable directly. See the docs for more information!

Packages

TUnit.Core

To be used when you want to define re-useable components, such as a test library, but it wouldn't be run as its own test suite.

TUnit.Engine

For test suites. This contains the test execution logic and test adapter. Only install this on actual test projects you intend to run, not class libraries.

TUnit.Assertions

This is independent from the framework and can be used wherever - Even in other test frameworks. It is just an assertion library used to assert data is as you expect. It uses an asychronous syntax which may be different to other assertion libraries you may have used.

TUnit

This is a helper package to combine the above 3 packages. If you just want a standard test app where you can write, run and assert tests, just install this!

TUnit.Playwright

This provides you base classes, similarly to Microsoft.Playwright.NUnit or Microsoft.Playwright.MSTest, to automatically create and dispose of Playwright objects in tests, to make it easier for you to write tests without worrying about lifecycles or disposing. The base classes are named the same as the other libraries: PageTest, ContextTest, BrowserTest, and PlaywrightTest.

Features

  • Native AOT / Trimmed Single File application support
  • Source generated tests
  • Property injection
  • Full async support
  • Parallel by default, with mechanisms to:
    • Run specific tests completely on their own
    • Run specific tests not in parallel with other specific tests
    • Limit the parallel limit on a per-test, class or assembly level
  • Tests can depend on other tests to form chains, useful for if one test depends on state from another action. While not recommended for unit tests, this can be useful in integration testing where state matters
  • Easy to read assertions - though you're also free to use whichever assertion library you like
  • Injectable test data via classes, methods, compile-time args, or matrices
  • Hooks before and after:
    • TestDiscover
    • TestSession
    • Assembly
    • Class
    • Test
  • Designed to avoid common pitfalls such as leaky test states
  • Dependency injection support (See here)
  • Ability to view and interrogate metadata and results from various assembly/class/test context objects

Installation

dotnet add package TUnit --prerelease

Example test

    private static readonly TimeOnly Midnight = TimeOnly.FromTimeSpan(TimeSpan.Zero);
    private static readonly TimeOnly Noon = TimeOnly.FromTimeSpan(TimeSpan.FromHours(12));
    
    [Test]
    public async Task IsMorning()
    {
        var time = GetTime();

        await Assert.That(time).IsAfterOrEqualTo(Midnight)
            .And.IsBefore(Noon);
    }

or with more complex test orchestration needs

    [Before(Class)]
    public static async Task ClearDatabase(ClassHookContext context) { ... }

    [After(Class)]
    public static async Task AssertDatabaseIsAsExpected(ClassHookContext context) { ... }

    [Before(Test)]
    public async Task CreatePlaywrightBrowser(TestContext context) { ... }

    [After(Test)]
    public async Task DisposePlaywrightBrowser(TestContext context) { ... }

    [Retry(3)]
    [Test, DisplayName("Register an account")]
    [MethodData(nameof(GetAuthDetails))]
    public async Task Register(string username, string password) { ... }

    [Repeat(5)]
    [Test, DependsOn(nameof(Register))]
    [MethodData(nameof(GetAuthDetails))]
    public async Task Login(string username, string password) { ... }

    [Test, DependsOn(nameof(Login), [typeof(string), typeof(string)])]
    [MethodData(nameof(GetAuthDetails))]
    public async Task DeleteAccount(string username, string password) { ... }

    [Category("Downloads")]
    [Timeout(300_000)]
    [Test, NotInParallel(Order = 1)]
    public async Task DownloadFile1() { ... }

    [Category("Downloads")]
    [Timeout(300_000)]
    [Test, NotInParallel(Order = 2)]
    public async Task DownloadFile2() { ... }

    [Repeat(10)]
    [Test]
    [Arguments(1)]
    [Arguments(2)]
    [Arguments(3)]
    [DisplayName("Go to the page numbered $page")]
    public async Task GoToPage(int page) { ... }

    [Category("Cookies")]
    [Test, Skip("Not yet built!")]
    public async Task CheckCookies() { ... }

    [Test, Explicit, WindowsOnlyTest, RetryHttpServiceUnavailable(5)]
    [Property("Some Key", "Some Value")]
    public async Task Ping() { ... }

    [Test]
    [ParallelLimit<LoadTestParallelLimit>]
    [Repeat(1000)]
    public async Task LoadHomepage() { ... }

    public static IEnumerable<(string Username, string Password)> GetAuthDetails()
    {
        yield return ("user1", "password1");
        yield return ("user2", "password2");
        yield return ("user3", "password3");
    }

    public class WindowsOnlyTestAttribute : SkipAttribute
    {
        public WindowsOnlyTestAttribute() : base("Windows only test")
        {
        }

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

    public class RetryHttpServiceUnavailableAttribute : RetryAttribute
    {
        public RetryHttpServiceUnavailableAttribute(int times) : base(times)
        {
        }

        public override Task<bool> ShouldRetry(TestInformation testInformation, Exception exception, int currentRetryCount)
        {
            return Task.FromResult(exception is HttpRequestException { StatusCode: HttpStatusCode.ServiceUnavailable });
        }
    }

    public class LoadTestParallelLimit : IParallelLimit
    {
        public int Limit => 50;
    }

Motivations

TUnit is inspired by NUnit and xUnit - two of the most popular testing frameworks for .NET.

It aims to build upon the useful features of both while trying to address any pain points that they may have.

Read more here

Prerelease

You'll notice that version 1.0 isn't out yet. While this framework is mostly feature complete, I'm waiting for a few things:

  • Full Rider support for all features
  • Full VS support for all features
  • Open to feedback on existing features
  • Open to ideas on new features

As such, the API may change. I'll try to limit this but it's a possibility.

Benchmark

Scenario: Building the test project

macos-latest


BenchmarkDotNet v0.14.0, macOS Sonoma 14.7.1 (23H222) [Darwin 23.6.0]
Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), Arm64 RyuJIT AdvSIMD
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), Arm64 RyuJIT AdvSIMD

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev Median
Build_TUnit 1,260.2 ms 46.12 ms 135.27 ms 1,271.9 ms
Build_NUnit 910.6 ms 48.97 ms 137.32 ms 854.1 ms
Build_xUnit 895.3 ms 17.86 ms 49.49 ms 883.0 ms
Build_MSTest 899.6 ms 17.86 ms 35.25 ms 893.1 ms

ubuntu-latest


BenchmarkDotNet v0.14.0, Ubuntu 22.04.5 LTS (Jammy Jellyfish)
AMD EPYC 7763, 1 CPU, 4 logical and 2 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev
Build_TUnit 1.807 s 0.0346 s 0.0462 s
Build_NUnit 1.478 s 0.0151 s 0.0133 s
Build_xUnit 1.493 s 0.0105 s 0.0098 s
Build_MSTest 1.576 s 0.0177 s 0.0166 s

windows-latest


BenchmarkDotNet v0.14.0, Windows 10 (10.0.20348.2849) (Hyper-V)
AMD EPYC 7763, 1 CPU, 4 logical and 2 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev
Build_TUnit 1.827 s 0.0343 s 0.0304 s
Build_NUnit 1.498 s 0.0273 s 0.0255 s
Build_xUnit 1.510 s 0.0279 s 0.0261 s
Build_MSTest 1.555 s 0.0273 s 0.0255 s

Scenario: A single test that completes instantly (including spawning a new process and initialising the test framework)

macos-latest


BenchmarkDotNet v0.14.0, macOS Sonoma 14.7.1 (23H222) [Darwin 23.6.0]
Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), Arm64 RyuJIT AdvSIMD
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), Arm64 RyuJIT AdvSIMD

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev
TUnit_AOT 176.3 ms 19.05 ms 56.18 ms
TUnit 759.2 ms 46.74 ms 137.09 ms
NUnit 1,228.5 ms 68.27 ms 200.21 ms
xUnit 882.8 ms 27.64 ms 80.63 ms
MSTest 744.0 ms 14.78 ms 34.84 ms

ubuntu-latest


BenchmarkDotNet v0.14.0, Ubuntu 22.04.5 LTS (Jammy Jellyfish)
AMD EPYC 7763, 1 CPU, 4 logical and 2 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev
TUnit_AOT 29.82 ms 0.304 ms 0.254 ms
TUnit 828.14 ms 16.271 ms 21.721 ms
NUnit 1,294.17 ms 11.658 ms 10.905 ms
xUnit 1,271.22 ms 13.461 ms 11.933 ms
MSTest 1,145.31 ms 9.675 ms 8.576 ms

windows-latest


BenchmarkDotNet v0.14.0, Windows 10 (10.0.20348.2849) (Hyper-V)
AMD EPYC 7763, 1 CPU, 4 logical and 2 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev Median
TUnit_AOT 77.63 ms 1.514 ms 2.021 ms 77.98 ms
TUnit 831.24 ms 16.562 ms 24.276 ms 843.95 ms
NUnit 1,306.17 ms 13.449 ms 12.580 ms 1,304.18 ms
xUnit 1,277.78 ms 8.779 ms 8.212 ms 1,278.37 ms
MSTest 1,164.78 ms 15.263 ms 14.277 ms 1,162.67 ms

Scenario: A test that takes 50ms to execute, repeated 100 times (including spawning a new process and initialising the test framework)

macos-latest


BenchmarkDotNet v0.14.0, macOS Sonoma 14.7.1 (23H222) [Darwin 23.6.0]
Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), Arm64 RyuJIT AdvSIMD
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), Arm64 RyuJIT AdvSIMD

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev
TUnit_AOT 263.0 ms 12.40 ms 36.57 ms
TUnit 629.6 ms 19.15 ms 55.55 ms
NUnit 13,988.9 ms 275.38 ms 394.94 ms
xUnit 14,283.1 ms 283.57 ms 559.74 ms
MSTest 14,332.7 ms 281.82 ms 500.94 ms

ubuntu-latest


BenchmarkDotNet v0.14.0, Ubuntu 22.04.5 LTS (Jammy Jellyfish)
AMD EPYC 7763, 1 CPU, 4 logical and 2 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev Median
TUnit_AOT 105.5 ms 2.07 ms 3.04 ms 107.2 ms
TUnit 897.4 ms 17.17 ms 23.50 ms 897.5 ms
NUnit 6,465.2 ms 13.76 ms 12.19 ms 6,461.6 ms
xUnit 6,510.5 ms 34.50 ms 32.28 ms 6,521.1 ms
MSTest 6,452.2 ms 21.90 ms 20.48 ms 6,448.0 ms

windows-latest


BenchmarkDotNet v0.14.0, Windows 10 (10.0.20348.2849) (Hyper-V)
AMD EPYC 7763, 1 CPU, 4 logical and 2 physical cores
.NET SDK 9.0.100
  [Host]   : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  .NET 9.0 : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Job=.NET 9.0  Runtime=.NET 9.0  

Method Mean Error StdDev Median
TUnit_AOT 136.2 ms 2.71 ms 5.60 ms 140.0 ms
TUnit 883.3 ms 17.34 ms 27.50 ms 889.2 ms
NUnit 7,458.8 ms 20.13 ms 17.84 ms 7,461.9 ms
xUnit 7,443.5 ms 14.48 ms 13.54 ms 7,443.2 ms
MSTest 7,421.3 ms 22.01 ms 19.51 ms 7,420.9 ms