📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

xUnit, NUnit and MSTest: how do they differ? Compare the test lifecycle (instances, setup and teardown), shared fixtures, parameterised tests and parallelism, and explain what changed in xUnit v3.

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.

Junior Theory Beginner microsoft-testing-platform mstest nunit test-frameworks testing xunit

🎯 Key points

  • xUnit and MSTest create a new class instance per test; NUnit shares one instance per fixture by default
  • xUnit setup is constructor / IDisposable / IAsyncLifetime; NUnit [SetUp]/[OneTimeSetUp]; MSTest [TestInitialize]/[ClassInitialize]
  • Shared expensive state: IClassFixture, ICollectionFixture and v3 assembly fixtures in xUnit
  • Data-driven tests: [Theory]+[InlineData]/[MemberData], [TestCase]/[TestCaseSource], [DataRow]/[DynamicData]
  • xUnit runs test collections (classes) in parallel by default; NUnit and MSTest parallelism is opt-in
  • Per-test isolation prevents order- and timing-dependent (flaky) failures under parallel runs
  • xUnit v3: executable test projects, TestContext.Current, Assert.Skip/SkipUnless/SkipWhen, Microsoft.Testing.Platform support

⏱ 30-second answer

All three are mature, free, open-source frameworks that run under dotnet test; the real differences are lifecycle and defaults.

  • xUnit creates a new instance of the test class for every test, uses the constructor and IDisposable/IAsyncLifetime for setup, shares expensive state through IClassFixture<T> and ICollectionFixture<T>, and runs classes in parallel by default.
  • NUnit keeps one instance per fixture unless you opt into InstancePerTestCase, so fields leak between tests; parallelism is opt-in with [Parallelizable].
  • MSTest is per-test-instance like xUnit, with [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).

🗣 Full answer (senior)

How I would answer this in an interview

"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 is Dispose or DisposeAsync, and if something is expensive, like a database container, you share it explicitly with IClassFixture<T> for one class or ICollectionFixture<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.Current with a cancellation token, Assert.Skip for 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."


Lifecycle side by side

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]

Data-driven tests

Framework Inline values From code
xUnit [Theory] + [InlineData] [MemberData], [ClassData], TheoryData<T>
NUnit [TestCase] [TestCaseSource]
MSTest [DataRow] [DynamicData]

Parallelism

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]

What changed in xUnit v3

  • Packages are 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.
  • Assembly fixtures for state shared across the whole run.
  • Microsoft.Testing.Platform (MTP) support; xUnit v3 4.0 (August 2026) defaults to MTP v2. On the .NET 10 SDK you opt dotnet test into MTP with the test.runner setting in global.json.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands how test frameworks isolate and run tests, not just which attributes to type.

Green flags

  • Explains per-test versus per-fixture instances and why it matters
  • Knows how xUnit shares expensive state (IClassFixture, ICollectionFixture, IAsyncLifetime)
  • Knows xUnit parallelises by class and NUnit/MSTest are opt-in
  • Mentions xUnit v3 or Microsoft.Testing.Platform

Red flags

  • Thinks the frameworks are interchangeable with no behavioural difference
  • Puts database setup in a constructor that runs per test
  • Uses static fields for shared state without seeing the risk

📚 Learn in depth

1. What a test framework actually does

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.

2. Why per-test instances matter

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.

3. Fixtures and their lifetimes

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.
  • Assembly fixture (v3): one per test run.

If T implements IAsyncLifetime, xUnit awaits InitializeAsync and DisposeAsync, which is how Testcontainers fixtures start a container once.

4. Parallelism model

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.

5. Licensing and maintenance

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.

Try it yourself

  1. Write an NUnit fixture with a 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)].
  2. Port the same tests to xUnit v3 and confirm each test gets a fresh list.
  3. Add an IClassFixture<T> whose constructor writes a timestamp; log it from three tests to prove it is created once.
  4. Add Thread.Sleep(2000) to tests in two different xUnit classes and time the run with and without [Collection("Serial")] on both.
  5. Run an xUnit v3 test project directly with dotnet run and look at the command-line options it offers.

💻 Code

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" }
}

⚠ Common mistakes

  • Mistake: Assuming NUnit creates a new instance per test. Why it is wrong: NUnit shares one fixture instance by default, so fields carry state between tests and results depend on order. Instead: Reset state in [SetUp] or use [FixtureLifeCycle(LifeCycle.InstancePerTestCase)].
  • Mistake: Putting expensive setup in an xUnit constructor. Why it is wrong: The constructor runs before every test, so a database or container is created dozens of times. Instead: Move it into an IClassFixture<T> or ICollectionFixture<T> with IAsyncLifetime.
  • Mistake: Sharing mutable static fields between test classes. Why it is wrong: xUnit runs classes in parallel, so statics cause random failures. Instead: Keep state in fixtures or per-test instances, or group the classes in one [Collection].
  • Mistake: Mixing two or three frameworks in one solution. Why it is wrong: Different lifecycles, attributes and runner settings confuse the team and CI. Instead: Standardise on one framework and migrate gradually.
  • Mistake: Calling .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].
  • Mistake: Upgrading to xUnit v3 by only changing the package version. Why it is wrong: v3 uses 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.
  • Mistake: Choosing a framework for its assertion syntax. Why it is wrong: Assertions can come from any library; lifecycle and parallelism affect every test. Instead: Choose on isolation model and team familiarity.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions IClassFixture or ICollectionFixture. Why: Checks practical fixture design and the trade-off with parallelism.
    How to answer

    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.
    • xUnit v3 assembly fixture ([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.

  2. When: Candidate mentions running tests against a real database in CI. Why: Checks whether the candidate can take fixtures into real integration testing.
    How to answer

    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.

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me