Lesson 05 of 93 · 6 min read · Updated

xUnit v2 vs v3: ValueTask Lifetimes, TestContext.Current and Runtime Skips

xUnit v3 looks almost the same as v2 when you read a test: [Fact], [Theory] and Assert.Equal are all still there. The real changes are in the architecture and in how tests run. This lesson walks through a v3 test class and shows each change next to its v2 equivalent: the new IAsyncLifetime signatures, TestContext.Current, the test cancellation token and runtime skipping with Assert.SkipWhen.

Technical Requirements

  1. .NET 11 SDK (projects target net11.0)
  2. xunit.v3 4.0.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0 (to run under dotnet test with VSTest)
  4. coverlet.collector 10.1.1 (optional)

What Changes, and What Does Not

The way you write a test stays the same. Arrange-Act-Assert does not care which major version of the framework you use. What changes is this:

  1. A v3 test project is an executable (OutputType is Exe). You can start it directly with dotnet run.
  2. Microsoft.Testing.Platform (MTP) support is built in. The project can still run through the VSTest adapter.
  3. IAsyncLifetime returns ValueTask instead of Task, and it now derives from IAsyncDisposable.
  4. TestContext.Current gives you the running test, its cancellation token and its output from anywhere.
  5. Assert.Skip and Assert.SkipWhen let a test decide at run time that it should be skipped.

The Project File

M01.Foundations.XUnitV3Examples/M01.Foundations.XUnitV3Examples.csproj

<PropertyGroup>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>

<IsTestingPlatformApplication>false</IsTestingPlatformApplication>
<UseMicrosoftTestingPlatformRunner>false</UseMicrosoftTestingPlatformRunner>
</PropertyGroup>

<ItemGroup>
<!-- xunit.v3: framework + built-in MTP runner -->
<PackageReference Include="xunit.v3" />
<!-- VSTest adapter: for "dotnet test" (VSTest mode) and IDEs -->
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="coverlet.collector" />
</ItemGroup>

<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>

The package is xunit.v3, not xunit. The two MTP properties are set to false so the project runs under the classic VSTest mode like the rest of the solution. The next lesson explains these properties and the three ways to run this project.

Async Lifetime with ValueTask

M01.Foundations.XUnitV3Examples/XUnitV3FeatureTests.cs

using M01.Foundations.Domain;

namespace M01.Foundations.XUnitV3Examples;

[Trait("Kapsam", "Unit")]
public class XUnitV3FeatureTests : IAsyncLifetime
{
private decimal _threshold;

// v2: Task InitializeAsync() v3: ValueTask InitializeAsync()
public ValueTask InitializeAsync()
{
_threshold = DiscountPolicy.Threshold;
return ValueTask.CompletedTask;
}

// v2: Task DisposeAsync() v3: ValueTask DisposeAsync() (IAsyncDisposable)
public ValueTask DisposeAsync() => ValueTask.CompletedTask;

[Fact]
public void CalculateDiscount_WhenSubtotalIsExactlyThreshold_AppliesDiscount()
{
// Written exactly as in v2: the framework changes, AAA does not.
var discount = DiscountPolicy.CalculateDiscount(_threshold);

Assert.Equal(100m, discount);
}

IAsyncLifetime is how a test class does asynchronous setup and cleanup, for example starting a container or seeding a database. In v3 both methods return ValueTask. Because the interface now derives from IAsyncDisposable, DisposeAsync is the standard IAsyncDisposable.DisposeAsync. When you migrate, every class that implements IAsyncLifetime fails to compile until you change Task to ValueTask. That is a good thing: the compiler gives you the full list of places to fix.

TestContext.Current and the Cancellation Token

M01.Foundations.XUnitV3Examples/XUnitV3FeatureTests.cs

[Fact]
public void TestContext_ExposesCurrentTestInformation()
{
// In v3 you do not have to inject ITestOutputHelper into the constructor.
var context = TestContext.Current;

context.TestOutputHelper?.WriteLine("Bu satır test çıktısına yazılır.");

Assert.Equal(nameof(TestContext_ExposesCurrentTestInformation), context.TestMethod?.MethodName);
}

[Fact]
public async Task CancellationToken_ComesFromTestContext()
{
// v3: this token fires if the test times out or is cancelled.
// Passing it to async calls lets stuck tests shut down cleanly.
var token = TestContext.Current.CancellationToken;

await Task.Delay(1, token);

Assert.False(token.IsCancellationRequested);
}

In v2, the only way to write to the test output was to take an ITestOutputHelper in the constructor and keep it in a field. In v3, TestContext.Current is available from anywhere during a test, including helper methods and fixtures. It also tells you which test is running, through TestMethod. The string passed to WriteLine means "This line is written to the test output."

The cancellation token matters more than it looks. When a test run is cancelled, or a test exceeds its timeout, xUnit v3 signals this token. If you pass it to HttpClient, EF Core or Task.Delay, a stuck test stops quickly instead of blocking the whole run. Make it a habit to pass TestContext.Current.CancellationToken to every async call in a test.

Skipping at Run Time

M01.Foundations.XUnitV3Examples/XUnitV3FeatureTests.cs

[Fact]
public void AssertSkipWhen_SkipsAtRuntime()
{
// In v2, Skip could only be a FIXED string on the attribute: [Fact(Skip = "...")].
// In v3 a test can be skipped AT RUN TIME based on a condition.
// Here the condition is always false, so the test runs normally and passes.
Assert.SkipWhen(Environment.GetEnvironmentVariable("M01_SKIP_DEMO") == "1",
"M01_SKIP_DEMO=1 ayarlandığı için atlandı.");

Assert.Equal(0m, DiscountPolicy.CalculateDiscount(999.99m));
}

[Theory]
[InlineData(2_500, 250)]
[InlineData(999.99, 0)]
public void CalculateDiscount_ReturnsExpectedAmount(double subtotal, double expected)
{
Assert.Equal((decimal)expected, DiscountPolicy.CalculateDiscount((decimal)subtotal));
}
}

[Fact(Skip = "...")] in v2 always skips. It cannot react to the machine the test runs on. Assert.SkipWhen(condition, reason) checks the condition while the test runs and reports the test as skipped, not as passed or failed. Typical uses are tests that need Docker, a specific operating system or a secret that exists only in CI. The reason string here means "Skipped because M01_SKIP_DEMO=1 is set." Set that environment variable to 1 and run the tests again to see the skip.

The [Theory] at the end is unchanged from v2. This is the point of the sample: most of your test code moves to v3 without edits.

Common Mistake: Mixing v2 and v3 in One Project

The xunit (v2) and xunit.v3 packages cannot live in the same project. In this solution, shared build settings add xUnit v2 automatically to every project whose name ends with .Tests. That is why this project is named M01.Foundations.XUnitV3Examples and deliberately does not end with .Tests. If you add v3 to a project that already gets v2 from a shared props file, you will get conflicting types such as two different FactAttribute classes.

When you migrate, check four things: the packages (xunit becomes xunit.v3), <OutputType>Exe</OutputType>, the target framework (net8.0 or later, or net472 or later) and the IAsyncLifetime signatures.

Summary

  1. Writing tests in xUnit v3 is almost identical to v2; the changes are in architecture and execution.
  2. A v3 test project is an executable and has built-in Microsoft.Testing.Platform support.
  3. IAsyncLifetime now returns ValueTask and derives from IAsyncDisposable.
  4. TestContext.Current exposes the running test, its output and a cancellation token you should pass to async calls.
  5. Assert.SkipWhen skips a test at run time; never reference xunit and xunit.v3 from the same project.