Compares xUnit, NUnit and MSTest on test-class lifecycle, setup and teardown, shared fixtures, data-driven tests and parallel execution, and covers xUnit v3 and Microsoft.Testing.Platform on .NET 10.
All three are mature, free, open-source frameworks that run under dotnet test; the real differences are lifecycle and defaults.
IDisposable/IAsyncLifetime for setup, shares expensive state through IClassFixture<T> and ICollectionFixture<T>, and runs classes in parallel by default.InstancePerTestCase, so fields leak between tests; parallelism is opt-in with [Parallelizable].[TestInitialize]/[ClassInitialize], and parallelism is opt-in at assembly level.Per-test isolation matters because once tests run in parallel, any state shared between them makes results depend on timing and order, which is how flaky tests appear. xUnit v3 makes test projects standalone executables, adds TestContext.Current and dynamic skipping (Assert.Skip, Assert.SkipUnless, Assert.SkipWhen), and runs natively on Microsoft.Testing.Platform. The trade-off is isolation by default (xUnit) versus familiar attribute-style setup (NUnit/MSTest).
"All three frameworks discover tests through attributes, run under
dotnet test, and are free and open source, so the choice is less about features and more about defaults. The biggest difference is the lifecycle. xUnit creates a brand-new instance of the test class for every test method, so any field you set in the constructor is fresh each time. Setup is just the constructor, teardown isDisposeorDisposeAsync, and if something is expensive, like a database container, you share it explicitly withIClassFixture<T>for one class orICollectionFixture<T>across classes. MSTest also creates an instance per test and uses[TestInitialize]and[TestCleanup]. NUnit is the odd one out: by default it creates one instance per fixture, so a list you add to in one test is still there in the next unless you reset it in[SetUp]or use[FixtureLifeCycle(LifeCycle.InstancePerTestCase)].The second difference is parallelism. xUnit treats each test class as a collection and runs collections in parallel by default, with tests inside a class running one after another. NUnit needs
[Parallelizable], and MSTest needs[assembly: Parallelize]. That default matters: xUnit surfaces shared static state early, NUnit and MSTest let it hide until someone turns parallelism on.On .NET 10 I'd default to xUnit v3. Test projects are now executables, you get
TestContext.Currentwith a cancellation token,Assert.Skipfor runtime skips, assembly fixtures, and native Microsoft.Testing.Platform support, which is faster to start than the old VSTest host. The mistake I see is teams mixing frameworks in one solution or porting NUnit habits into xUnit, like putting setup in static fields. Pick one framework, and choose it for its isolation model, not its assertion syntax."
| Concern | xUnit (v3) | NUnit 4 | MSTest |
|---|---|---|---|
| Instance per | Test | Fixture (default) | Test |
| Per-test setup | Constructor | [SetUp] |
[TestInitialize] |
| Per-test teardown | Dispose / DisposeAsync |
[TearDown] |
[TestCleanup] |
| Async setup | IAsyncLifetime |
async [SetUp] |
async [TestInitialize] |
| Per-class shared state | IClassFixture<T> |
[OneTimeSetUp] |
static [ClassInitialize] |
| Cross-class shared state | ICollectionFixture<T> |
[SetUpFixture] |
[AssemblyInitialize] |
| Assembly-wide | [assembly: AssemblyFixture] (v3) |
[SetUpFixture] at root namespace |
[AssemblyInitialize] |
| Framework | Inline values | From code |
|---|---|---|
| xUnit | [Theory] + [InlineData] |
[MemberData], [ClassData], TheoryData<T> |
| NUnit | [TestCase] |
[TestCaseSource] |
| MSTest | [DataRow] |
[DynamicData] |
| Framework | Default | How to control |
|---|---|---|
| xUnit | Collections (classes) in parallel | [Collection("Db")] to serialise, xunit.runner.json maxParallelThreads |
| NUnit | Serial | [Parallelizable(ParallelScope.All)], [NonParallelizable] |
| MSTest | Serial | [assembly: Parallelize(Workers = 0, Scope = ExecutionScope.MethodLevel)], [DoNotParallelize] |
xunit.v3; the test project builds as an executable (OutputType=Exe), so you can run it directly.TestContext.Current gives the current test, output and a CancellationToken that fires on timeout or cancel.Assert.Skip/Assert.SkipWhen for dynamic skips, Explicit = true for tests that only run on request.dotnet test into MTP with the test.runner setting in global.json.A team moving 2,400 NUnit tests to xUnit v3 found 31 tests that only passed because an earlier test in the same fixture had populated a shared list. Once each test had its own instance the hidden dependencies surfaced, and parallel execution cut the suite from 6 minutes to 2 minutes 40 seconds on the CI agent.
Checks whether the candidate understands how test frameworks isolate and run tests, not just which attributes to type.
Green flags
IClassFixture, ICollectionFixture, IAsyncLifetime)Red flags
A .NET test framework is three pieces:
[attributes in your code]
|
discovery (reflection or source generation)
|
execution engine (lifecycle, parallelism, fixtures)
|
runner / host ---> results (TRX, console, IDE)
(VSTest or Microsoft.Testing.Platform)
The framework owns discovery and execution; the host owns process start-up, filtering and reporting. Historically every framework plugged into VSTest through an adapter package (xunit.runner.visualstudio, NUnit3TestAdapter, MSTest.TestAdapter). Microsoft.Testing.Platform is the newer host: the test project is an executable that hosts the framework in-process, which starts faster and works without a separate testhost process.
xUnit's designers made the class instance the unit of isolation: if every test gets a new object, instance fields cannot leak. NUnit's default of one instance per fixture is cheaper but makes order matter:
NUnit default xUnit / MSTest
fixture instance A instance 1 -> Test1
Test1 (adds item) instance 2 -> Test2
Test2 (sees item!) instance 3 -> Test3
Static fields leak in every framework, which is why shared statics are the most common source of flaky parallel tests.
xUnit builds fixtures once and injects them through the constructor:
IClassFixture<T>: created before the first test in the class, disposed after the last.ICollectionFixture<T>: shared by every class in a [Collection]; those classes then run serially with each other.If T implements IAsyncLifetime, xUnit awaits InitializeAsync and DisposeAsync, which is how Testcontainers fixtures start a container once.
xUnit parallelises collections, not methods. Each class is its own collection unless you group classes with [Collection("name")]. Within a collection tests run sequentially. The thread count defaults to the processor count and is set with maxParallelThreads in xunit.runner.json. NUnit can parallelise down to individual tests (ParallelScope.All) and MSTest at class or method level.
All three are permissively licensed (xUnit Apache 2.0, NUnit MIT, MSTest MIT), actively maintained and supported by every IDE. MSTest ships MSTest.Sdk, an MSBuild project SDK that pulls in the framework, adapter and analysers in one line.
List<int> field, add to it in two tests, and watch the second test see the first one's data. Then add [FixtureLifeCycle(LifeCycle.InstancePerTestCase)].IClassFixture<T> whose constructor writes a timestamp; log it from three tests to prove it is created once.Thread.Sleep(2000) to tests in two different xUnit classes and time the run with and without [Collection("Serial")] on both.dotnet run and look at the command-line options it offers.An xUnit v3 test class showing per-test setup, an async shared fixture and a data-driven theory, with the code under test:
// PriceCalculator.cs (code under test)
namespace Shop.Pricing;
public sealed class PriceCalculator
{
public decimal ApplyGst(decimal net) =>
net < 0 ? throw new ArgumentOutOfRangeException(nameof(net)) : Math.Round(net * 1.10m, 2);
}
// PriceCalculatorTests.cs (xunit.v3)
using Shop.Pricing;
using Xunit;
namespace Shop.Pricing.Tests;
// Expensive shared state: created once per class, awaited before the first test.
public sealed class RatesFixture : IAsyncLifetime
{
public IReadOnlyDictionary<string, decimal> Rates { get; private set; } = new Dictionary<string, decimal>();
public ValueTask InitializeAsync()
{
Rates = new Dictionary<string, decimal> { ["AU"] = 0.10m };
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
public sealed class PriceCalculatorTests(RatesFixture rates) : IClassFixture<RatesFixture>
{
// A new PriceCalculatorTests instance (and so a new calculator) is created for every test.
private readonly PriceCalculator _sut = new();
[Theory]
[InlineData(100.00, 110.00)]
[InlineData(0.00, 0.00)]
[InlineData(9.99, 10.99)]
public void ApplyGst_adds_ten_percent(decimal net, decimal expected) =>
Assert.Equal(expected, _sut.ApplyGst(net));
[Fact]
public void ApplyGst_rejects_negative_amounts() =>
Assert.Throws<ArgumentOutOfRangeException>(() => _sut.ApplyGst(-1m));
[Fact]
public void Fixture_is_shared_and_initialised() =>
Assert.Equal(0.10m, rates.Rates["AU"]);
[Fact]
public void Skips_when_not_on_ci()
{
// v3 dynamic skip, decided at run time.
Assert.SkipUnless(Environment.GetEnvironmentVariable("CI") is not null, "Runs on CI only");
Assert.True(true);
}
}
// global.json: opt dotnet test into Microsoft.Testing.Platform on the .NET 10 SDK
{
"sdk": { "version": "10.0.100" },
"test": { "runner": "Microsoft.Testing.Platform" }
}
[SetUp] or use [FixtureLifeCycle(LifeCycle.InstancePerTestCase)].IClassFixture<T> or ICollectionFixture<T> with IAsyncLifetime.[Collection]..Result or .Wait() in setup because the framework's setup looked synchronous. Why it is wrong: It hides exceptions in AggregateException and can deadlock. Instead: Use IAsyncLifetime (xUnit) or async [SetUp]/[TestInitialize].xunit.v3 packages, an executable test project and changed APIs (ValueTask in IAsyncLifetime, ITestOutputHelper namespace). Instead: Follow the v3 migration guide and run the analysers.For a new .NET 10 codebase I default to xUnit v3: per-test isolation and parallel-by-default push teams towards independent tests from day one, and it is what most ASP.NET Core documentation and samples use. I would not migrate a healthy NUnit or MSTest suite just for fashion; the cost is real and the benefit is mostly consistency. MSTest is a fine choice where the team values first-party Microsoft support and MSTest.Sdk.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| xUnit v3 | New projects, ASP.NET Core, teams that want strict isolation | Learning fixture injection; v2 to v3 migration | Team deeply invested in NUnit constraint model |
| NUnit 4 | Existing NUnit suites, rich Assert.That constraints |
Shared fixture instance by default | When parallel isolation is a priority and the team is new to it |
| MSTest (MSTest.Sdk) | Microsoft-first shops, MTP native, Visual Studio users | Fewer community extensions | When you depend on xUnit-specific libraries |
To measure, track suite wall time and flaky-test rate before and after any change of framework or parallel settings.
Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:
IClassFixture<T>: one instance per test class.ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.[assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.
Add the Testcontainers.MsSql package. In an xUnit collection fixture that implements IAsyncLifetime, build an MsSqlContainer with a pinned image, await StartAsync() in InitializeAsync, and await DisposeAsync() in teardown (Testcontainers' Ryuk reaper also removes orphaned containers if a CI job dies). Pass GetConnectionString() to a WebApplicationFactory by overriding configuration, apply EF Core migrations once, and reset data between tests with Respawn. If the container fails to start (for example the CI agent has no Docker), fail fast with a clear message rather than skipping. Each run gets a clean, real SQL Server, catching translation and constraint bugs that the in-memory provider hides.
Last updated 23 Nov 2026.