Use Microsoft.Extensions.DependencyInjection to resolve xUnit test cases: constructor-inject services into your test classes instead of writing them by hand, and reuse the same Startup/host configuration you use in your application.
xUnit v2 users: please use the v2 branch.
Xunit.DependencyInjection.SkippableFactis obsolete on xunit.v3 and no longer needed.
Install the NuGet package:
dotnet add package Xunit.DependencyInjection
dotnet add package xunit.v3 --version 4.0.0xUnit v4 uses the
xunit.v3package. When upgrading, replace anyxunit.v3.mtp-v2reference withxunit.v3.
Add a Startup class to your test project and register your services in ConfigureServices:
namespace Your.Test.Project
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDependency, DependencyClass>();
}
}
}Then inject IDependency into your test class constructor, exactly like you would with any other DI-enabled class:
public interface IDependency
{
int Value { get; }
}
internal class DependencyClass : IDependency
{
public int Value => 1;
}
public class MyAwesomeTests
{
private readonly IDependency _d;
public MyAwesomeTests(IDependency d) => _d = d;
[Fact]
public void AssertThatWeDoStuff()
{
Assert.Equal(1, _d.Value);
}
}
Xunit.DependencyInjectionbuilds on top of the generic host and fully supports its lifecycle, so you can use any feature the generic host offers, including (but not limited to)IHostedService.
dotnet add package Microsoft.AspNetCore.TestHostpublic class Startup
{
public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
.ConfigureWebHost[Defaults](webHostBuilder => webHostBuilder
.UseTestServer(options => options.PreserveExecutionContext = true)
.UseStartup<AspNetCoreStartup>());
}If your web project uses Minimal APIs instead of an ASP.NET Core Startup class, install Xunit.DependencyInjection.AspNetCoreTesting:
dotnet add package Xunit.DependencyInjection.AspNetCoreTestingpublic class Startup
{
public IHostBuilder CreateHostBuilder() => MinimalApiHostBuilderFactory.GetHostBuilder<Program>();
}Your ASP.NET Core project may need to add
InternalsVisibleTofor the test project, or addpublic partial class Program { }at the end ofProgram.cs, so the test project can referenceProgram.See Xunit.DependencyInjection.Test.AspNetCore for a full example.
Startup supports two configuration styles. The Configure method (see Initializing data on startup) is supported by both styles.
-
CreateHostApplicationBuildermethodIf this method is not found, the host falls back to
Host.CreateEmptyApplicationBuilder(new() { ApplicationName = assemblyName.Name }).public HostApplicationBuilder CreateHostApplicationBuilder([AssemblyName assemblyName]) { }
-
ConfigureHostApplicationBuildermethod (presence of this method selects theHostApplicationBuilderstyle)public void ConfigureHostApplicationBuilder(IHostApplicationBuilder hostApplicationBuilder) { }
-
BuildHostApplicationBuildermethodIf this method is not found, the host is built by simply calling
hostApplicationBuilder.Build().public IHost BuildHostApplicationBuilder(HostApplicationBuilder hostApplicationBuilder) { return hostApplicationBuilder.Build(); }
-
CreateHostBuildermethodpublic class Startup { public IHostBuilder CreateHostBuilder([AssemblyName assemblyName]) { } }
-
ConfigureHostmethodpublic class Startup { public void ConfigureHost(IHostBuilder hostBuilder) { } }
-
ConfigureServicesmethodpublic class Startup { public void ConfigureServices(IServiceCollection services[, HostBuilderContext context]) { } }
-
BuildHostmethodIf this method is not found, the host is built by simply calling
hostBuilder.Build().public class Startup { public IHost BuildHost([IHostBuilder hostBuilder]) { return hostBuilder.Build(); } }
Method parameters wrapped in [...] above are optional.
Startup classes are looked up in the following order; the first match wins.
Apply [Startup(typeof(MyStartup))] on the test class.
public class TestClass1
{
public class Startup
{
public void ConfigureServices(IServiceCollection services) { }
}
}If the test class's full name is A.B.C.TestClass, Startup is looked up in this order:
A.B.C.StartupA.B.StartupA.StartupStartup
A default
Startupwas required before 8.7.0, and is optional in some cases after 8.7.0. When it's required, add a startup class to your test project as shown above.
By default, Your.Test.Project.Startup, Your.Test.Project is used.
If you want to use a custom Startup, set XunitStartupAssembly and/or XunitStartupFullName in your project's PropertyGroup:
<Project>
<PropertyGroup>
<XunitStartupAssembly>Abc</XunitStartupAssembly>
<XunitStartupFullName>Xyz</XunitStartupFullName>
</PropertyGroup>
</Project>| XunitStartupAssembly | XunitStartupFullName | Resulting Startup |
|---|---|---|
Your.Test.Project.Startup, Your.Test.Project |
||
Abc |
Abc.Startup, Abc |
|
Xyz |
Xyz, Your.Test.Project |
|
Abc |
Xyz |
Xyz, Abc |
By default, xUnit runs tests from different test collections in parallel, while tests in the same class run sequentially. xUnit v4 supports three parallelization modes:
ParallelMode.None: Run all tests sequentially.ParallelMode.Collections(default): Run different test collections in parallel.ParallelMode.All: Run all tests in parallel, including tests in the same class.
Configure the mode with xUnit's assembly-level Parallelization attribute:
using Xunit.v3;
[assembly: Parallelization(MaxThreads = 2, Mode = ParallelMode.All)]MaxThreads is optional; set it to limit the number of tests running concurrently. Remove the ParallelizationMode MSBuild property when upgrading, as it no longer controls parallelization.
If you register a custom
ITestCollectionOrderer, test collections run in the order it specifies, which can be slower than running without one.
To run tests in a class or method sequentially when using ParallelMode.All, decorate it with [DisableParallelization]. To prevent a test collection from running in parallel with other tests, use [CollectionDefinition(DisableParallelization = true)].
See xUnit's parallelization documentation for Parallelization.Algorithm and runner-specific configuration.
Thanks to Meziantou.Xunit.ParallelTestFramework for the inspiration.
<Project>
<PropertyGroup>
<EnableXunitDependencyInjectionDefaultTestFrameworkAttribute>false</EnableXunitDependencyInjectionDefaultTestFrameworkAttribute>
</PropertyGroup>
</Project>Inject ITestOutputHelperAccessor instead of ITestOutputHelper directly, since the actual instance is only available while a test is running:
internal class DependencyClass : IDependency
{
private readonly ITestOutputHelperAccessor _testOutputHelperAccessor;
public DependencyClass(ITestOutputHelperAccessor testOutputHelperAccessor)
{
_testOutputHelperAccessor = testOutputHelperAccessor;
}
}Install Xunit.DependencyInjection.Logging:
dotnet add package Xunit.DependencyInjection.LoggingThe call chain must originate from the running test case; otherwise this feature won't work.
public class Startup
{
public void ConfigureServices(IServiceCollection services) => services
.AddLogging(lb => lb.AddXunitOutput());
}public class Startup
{
public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
.ConfigureServices((context, services) => { /* use context.Configuration / context.HostingEnvironment */ });
}or
public class Startup
{
public void ConfigureServices(IServiceCollection services, HostBuilderContext context)
{
// use context.Configuration / context.HostingEnvironment
}
}public class Startup
{
public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
.ConfigureHostConfiguration(builder => { })
.ConfigureAppConfiguration((context, builder) => { });
}[MemberData] members are static and can't be resolved from the container, so use [MethodData] instead — it resolves the referenced method's parameters from DI.
Register the Xunit.DependencyInjection activity source with your TracerProviderBuilder to capture the spans this library emits:
TracerProviderBuilder builder;
builder.AddSource("Xunit.DependencyInjection");Inherit from BeforeAfterTest and register your implementation as a BeforeAfterTest service.
For synchronous initialization, use the Configure method. For asynchronous initialization, use an IHostedService.
| Package | Description |
|---|---|
| Xunit.DependencyInjection.Logging | Write Microsoft.Extensions.Logging output to ITestOutputHelper, see above |
| Xunit.DependencyInjection.AspNetCoreTesting | Integration with ASP.NET Core Minimal API TestHost, see above |
| Xunit.DependencyInjection.StaFact | Run [StaFact]/[StaTheory] test cases on an STA thread (e.g. for UI tests) |
| Xunit.DependencyInjection.xRetry | Support xRetry's [RetryFact]/[RetryTheory] |
| Xunit.DependencyInjection.FsCheck | Support FsCheck property-based [Property] tests |
| Xunit.DependencyInjection.Demystifier | Use Ben.Demystifier to format exception stack traces |
| Xunit.DependencyInjection.Analyzer | Roslyn analyzer that validates Startup class shape at compile time |
| Xunit.DependencyInjection.Template | dotnet new xunit-di template to scaffold a new test project |
dotnet add package Xunit.DependencyInjection.StaFactpublic class Startup
{
public void ConfigureServices(IServiceCollection services) => services.AddStaFactSupport();
}public class MyStaTests
{
[StaFact]
public void RunOnStaThread() { }
[StaTheory]
[InlineData(1)]
public void RunOnStaThread(int value) { }
}dotnet add package Xunit.DependencyInjection.xRetrypublic class Startup
{
public void ConfigureServices(IServiceCollection services) => services.AddXRetrySupport();
}public class MyRetryTests
{
[RetryFact(3)]
public void FlakyTest() { }
}dotnet add package Xunit.DependencyInjection.FsCheckpublic class Startup
{
public void ConfigureServices(IServiceCollection services) => services.AddFsCheckSupport();
}dotnet add package Xunit.DependencyInjection.Demystifierpublic class Startup
{
public void ConfigureServices(IServiceCollection services) => services.UseDemystifyExceptionFilter();
}The analyzer is automatically added as an analyzer reference when you install Xunit.DependencyInjection, and reports compile-time diagnostics (e.g. multiple Startup constructors, invalid Configure* method signatures) so misconfigured Startup classes are caught early.
dotnet new install Xunit.DependencyInjection.Template
dotnet new create xunit-di -n MyTestProjectSee Xunit.DependencyInjection.Template for details.