Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 14

    xUnit v3 Basics: Facts, Theories, Assertions and Running Tests on .NET 10

    What this lesson teaches

    In xUnit, Fact tests one case, while Theory runs the same test over data rows. Learn which to choose and how xUnit v3 runs tests on .NET 10.

    You will also learn how to check results, prepare fresh test objects, clean up resources, and configure a v3 project. The examples use the xunit.v3 package, version 4.0.2. The name v3 means the third generation of xUnit. It is not the package version number.

    What a test runner does

    A test runner finds test methods, executes them, and reports whether they pass. xUnit uses attributes such as [Fact] to recognize tests.

    Before using xUnit, try this small runner. Reflection lets a program inspect types and methods while it runs. Here, reflection finds methods marked [Check].

    This is a teaching example, not an xUnit replacement. Predict its totals before running it.

    C#Runs
    using System.Reflection;
    
    int passed = 0, failed = 0;
    foreach (var method in typeof(Checks).GetMethods().OrderBy(m => m.Name))
    {
        if (!method.IsDefined(typeof(CheckAttribute), false)) continue;
        try
        {
            method.Invoke(new Checks(), null);
            Console.WriteLine($"PASS {method.Name}");
            passed++;
        }
        catch (TargetInvocationException)
        {
            Console.WriteLine($"FAIL {method.Name}");
            failed++;
        }
    }
    Console.WriteLine($"{passed} passed, {failed} failed");
    public sealed class CheckAttribute : Attribute { }
    public sealed class Checks
    {
        private int count;
        [Check] public void A_First() { if (++count != 1) throw new Exception(); }
        [Check] public void B_Fresh() { if (++count != 1) throw new Exception(); }
        [Check] public void C_Fails() { throw new Exception("Deliberate failure"); }
    }
    Output
    PASS A_First
    PASS B_Fresh
    FAIL C_Fails
    2 passed, 1 failed

    The runner creates new Checks() for each method. Here, each new object has its own count field, initially zero.

    Both A_First and B_Fresh pass because neither uses the other's object. C_Fails deliberately throws. Reflection wraps that exception in TargetInvocationException, which the runner catches to report failure.

    flowchart LR
        A["Runner"] -->|"finds"| B["Next Check method"]
        A -->|"creates"| C["Fresh Checks object"]
        D["Runner calls method on that object"] -->|"produces"| E["PASS or FAIL counted"]

    Each marked method runs on a fresh object before the runner reports its result.

    The mistake to avoid. A normal return does not prove useful behavior was checked. A test needs an expectation that can fail.

    In an interview, say: “The runner discovers and executes tests. Assertions check expectations and fail the test when those expectations are not met.”

    Fact or Theory in xUnit?

    Use [Fact] for one case. Use [Theory] when the same test should run with several rows of inputs and expected results.

    [InlineData] puts a data row beside the test. [MemberData] gets rows from a named member, such as a public static property. [ClassData(typeof(MyRows))] reads rows from a separate class, which is useful when several test classes reuse the same rows. TheoryData<decimal, decimal> describes rows containing two decimal values.

    The following examples belong in the xUnit v3 project configured later. They do not run in the page's console runner.

    C#
    using Xunit;
    
    public sealed class NumberTests
    {
        [Fact]
        public void Abs_of_negative_three_is_three()
        {
            Assert.Equal(3, Math.Abs(-3));
        }
    
        [Theory]
        [InlineData(-3, 3)]
        [InlineData(0, 0)]
        [InlineData(5, 5)]
        public void Abs_returns_expected_number(int input, int expected)
        {
            Assert.Equal(expected, Math.Abs(input));
        }
    
        public static TheoryData<decimal, decimal> Prices => new()
        {
            { 10m, 12m },
            { 25m, 30m }
        };
    
        [Theory]
        [MemberData(nameof(Prices))]
        public void Price_includes_twenty_percent(decimal price, decimal expected)
        {
            Assert.Equal(expected, price * 1.2m);
        }
    }

    The Fact checks one specific input. The first Theory runs the same method for three rows. Each row supplies input and expected. The runner reports each row as a separate test, such as Abs_returns_expected_number(input: -3, expected: 3). One failing row does not hide the results of the others.

    The price Theory reads two rows from Prices.

    The C# specification's allowed attribute parameter types do not include decimal. Putting 10m in [InlineData] produces compiler error CS0182. MemberData avoids that restriction because the property creates ordinary decimal values.

    A Theory reduces repeated test code, but its rows should describe the same behavior. Separate tests are clearer when their preparation or expectations differ substantially. Microsoft's xUnit tutorial shows the transition from a Fact to data-driven tests.

    The mistake to avoid. Do not replace 10m with 10.0 just to make an attribute compile. The attribute then holds a double; xUnit converts it to decimal when the test runs, and only about 15 significant digits survive. Use decimal data through MemberData.

    In an interview, say: “A Fact tests one case. A Theory runs the same test over data rows. InlineData takes compile-time constants. MemberData reads a public static property or method, usually returning TheoryData. ClassData reads rows from a separate class and helps reuse data across test classes. For decimal values or complex objects, I use MemberData or ClassData.”

    Choose an assertion that states the expectation

    Prefer an assertion that names what you mean. Assert.Equal expresses equality more clearly than wrapping an equality comparison in Assert.True. If you expect 3 but get 4, the equality assertion shows Expected: 3 and Actual: 4. The true-or-false assertion only shows Expected: True and Actual: False, so you must work out which values differed.

    For doubles, use the version of Assert.Equal that takes a third argument, precision. It rounds both numbers to that many decimal places and then compares them. This matters because calculations such as 0.1 + 0.2 need not produce exactly the double represented by 0.3.

    The exception assertions below receive lambdas so xUnit can run the code and inspect what it throws.

    C#
    using Xunit;
    
    public sealed class AssertionTests
    {
        [Fact]
        public void Results_match_their_expectations()
        {
            Assert.Equal(4, 2 + 2);
            Assert.Equal(0.3, 0.1 + 0.2, precision: 10);
            Assert.True(8 > 3);
            Assert.Null(null);
            Assert.Single(new[] { "only item" });
        }
    
        [Fact]
        public void Throws_requires_the_exact_exception_type()
        {
            Assert.Throws<ArgumentException>(
                () => Raise(new ArgumentException("Invalid argument")));
        }
    
        [Fact]
        public void ThrowsAny_also_accepts_a_subclass()
        {
            Assert.ThrowsAny<ArgumentException>(
                () => Raise(new ArgumentOutOfRangeException("amount")));
        }
    
        private static void Raise(Exception exception) => throw exception;
    }

    Raise stands in for the code under test. A lambda that only throws would pick an async overload and not compile.

    Equal checks the expected value against the actual result. True checks that a condition is true. Null checks for null, and Single requires exactly one item.

    Assert.Throws<ArgumentException> requires exactly ArgumentException. It rejects ArgumentOutOfRangeException, even though that class derives from ArgumentException.

    Assert.ThrowsAny<ArgumentException> accepts ArgumentException or any class derived from it (a subclass), such as ArgumentOutOfRangeException. Choose it only when that broader promise is what you want to test. Neither example checks the exception message.

    The mistake to avoid. Do not assume Throws<T> accepts subclasses. Choosing ThrowsAny<T> also makes a weaker promise, so use it deliberately.

    In an interview, say: “Throws requires the exact exception type. ThrowsAny accepts that type or a subclass. I choose the assertion that matches the exact exception type my code promises to throw.”

    Setup, cleanup, and fresh test instances

    xUnit creates a new test-class instance for each test, including each Theory row. The constructor prepares that instance. Dispose performs synchronous cleanup after its test. Implementing IDisposable tells xUnit that the class supplies a Dispose method.

    C#
    using System.IO;
    using Xunit;
    
    public sealed class BufferTests : IDisposable
    {
        private readonly MemoryStream buffer;
    
        public BufferTests()
        {
            buffer = new MemoryStream();
            buffer.WriteByte(42);
            buffer.Position = 0;
        }
    
        [Fact]
        public void First_byte_is_available()
        {
            Assert.Equal(42, buffer.ReadByte());
        }
    
        [Fact]
        public void Another_test_also_starts_at_the_first_byte()
        {
            Assert.Equal(42, buffer.ReadByte());
        }
    
        public void Dispose()
        {
            buffer.Dispose();
        }
    }

    Both tests read 42. Each constructor creates and prepares a different stream, so the first test does not advance the second test's position.

    Use IAsyncLifetime when setup or cleanup needs to be awaited. In v3, IAsyncLifetime.InitializeAsync() and IAsyncLifetime.DisposeAsync() return ValueTask, unlike their v2 signatures. For asynchronous cleanup alone, v3 also supports IAsyncDisposable.

    Each test gets its own object, so its normal fields start fresh. Static fields belong to the type, not each object. They are not reset between tests: all tests share them.

    A fixture is an object whose lifetime xUnit manages for sharing across tests. Fixtures avoid repeatedly creating costly resources. But if a shared object holds data that tests can change, one test can change what the next test sees. See shared fixtures, parallelism, and test independence.

    The mistake to avoid. Do not assume a fresh test object resets static fields or shared fixtures. Those need their own isolation strategy.

    In an interview, say: “xUnit creates a new class instance per test, so ordinary fields do not leak between tests, but statics can. I use the constructor and Dispose for setup and cleanup, IAsyncLifetime for async work, and fixtures for costly shared objects.”

    Create and run an xUnit v3 project

    xUnit v3 test projects are executable projects. Do not assume the SDK's dotnet new xunit template creates v3.

    For these examples, create an empty folder and save this as Basics.Tests.csproj. Then place the test classes in .cs files in that folder. Do not add your own Main; the xUnit package supplies the entry point, where the executable starts.

    XML
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net10.0</TargetFramework>
        <OutputType>Exe</OutputType>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="xunit.v3" Version="4.0.2" />
      </ItemGroup>
    </Project>

    OutputType makes the project executable.

    From that folder, this command builds and runs the tests:

    Shell
    dotnet run

    To use dotnet test with this configuration on the .NET 10 SDK, save the following as global.json in the folder where you run dotnet test or in any folder above it (for example, the project or solution folder):

    JSON
    {
      "test": {
        "runner": "Microsoft.Testing.Platform"
      }
    }

    Microsoft.Testing.Platform, or MTP, is the test execution platform used by this configuration. VSTest is the older platform that dotnet test selects by default without a runner setting.

    Now run:

    Shell
    dotnet test

    Without the runner setting, this package configuration fails with “Testing with VSTest target is no longer supported.” This is a configuration failure, not a failed assertion. Microsoft's dotnet test documentation explains the two modes.

    The mistake to avoid. If dotnet new xunit gives you a v2 project, do not follow the v3 instructions without changing its configuration. Replace the xunit package with xunit.v3, set OutputType to Exe, and add the global.json runner setting shown above before running dotnet test.

    In an interview, say: “An xUnit v3 project is an executable, so dotnet run can execute its tests. For this configuration, dotnet test on the .NET 10 SDK needs Microsoft.Testing.Platform selected in global.json.”

    Other xUnit v3 changes you will meet

    ITestOutputHelper writes diagnostic text associated with a test. In v3, it is in the Xunit namespace, not Xunit.Abstractions.

    TestContext.Current.CancellationToken lets a test pass xUnit's cancellation request to operations that support it.

    Dynamic skipping means deciding during execution not to run the remainder of a test. Assert.Skip supplies that decision and a reason. An explicit test runs only when explicitly selected or enabled through the runner, rather than during an ordinary run.

    C#
    using System.Threading.Tasks;
    using Xunit;
    
    public sealed class V3FeatureTests
    {
        private readonly ITestOutputHelper output;
    
        public V3FeatureTests(ITestOutputHelper output)
        {
            this.output = output;
        }
    
        [Fact]
        public async Task Work_observes_test_cancellation()
        {
            output.WriteLine("Starting cancellable work");
            await Task.Delay(1, TestContext.Current.CancellationToken);
        }
    
        [Fact]
        public void Unavailable_environment_is_skipped()
        {
            Assert.Skip("The required environment is unavailable.");
        }
    
        [Fact(Explicit = true)]
        public void Runs_only_when_explicitly_requested()
        {
            Assert.Equal(4, 2 + 2);
        }
    }

    xUnit supplies the output helper through the constructor. The first test awaits an operation that accepts the test's cancellation token. The second demonstrates skipping unconditionally; a real environment check would decide whether to call Assert.Skip.

    Do not write async void tests in v3. Use async Task or async ValueTask.

    The mistake to avoid. A skipped or explicit test has not proved the behavior works. Keep skips visible and justified rather than using them to hide failures.

    In an interview, say: “v3 uses executable projects and ValueTask lifetime methods. It adds TestContext, dynamic skipping, and explicit tests. ITestOutputHelper moved to Xunit, and async void tests are no longer supported.”

    Check yourself

    Which choice lets an xUnit Theory receive decimal values such as 12.50m?

    A Use MemberData backed by TheoryData<decimal>
    B Write 12.50m directly in an InlineData attribute
    C Use InlineData with a const decimal field instead
    D Use a [Fact] method that takes a decimal parameter
    Show answer

    Correct answer: A

    Decimal values cannot be attribute arguments. MemberData supplies them from ordinary code, and TheoryData<decimal> describes rows containing one decimal value.

    A test throws ArgumentOutOfRangeException. Which assertion accepts it when the requested exception type is ArgumentException?

    A Assert.Throws<ArgumentException>
    B Assert.ThrowsAsync<ArgumentException>
    C Assert.ThrowsAny<ArgumentException>
    D Assert.IsType<ArgumentException>
    Show answer

    Correct answer: C

    ThrowsAny accepts the requested type or a subclass. Throws requires the exact requested type.

    Going deeper

    Version 4.0.0 of xunit.v3 was released on 14 August 2026 under the Apache-2.0 license; 4.0.3 (9 November 2026) is the newest today. The examples were built with 4.0.2.

    Sources

    Practice

    Practice test: Practice: xUnit v3 Basics: Facts, Theories, Assertions and Running Tests on .NET 108 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 30 Nov 2026 ·