MyGit

pengweiqhca/Xunit.DependencyInjection

Fork: 49 Star: 372 (更新于 2024-12-02 05:31:47)

license: MIT

Language: C# .

Use Microsoft.Extensions.DependencyInjection to resolve xUnit test cases.

最后发布版本: 9.3.0 ( 2024-05-14 09:07:59)

GitHub网址

Use Microsoft.Extensions.DependencyInjection to resolve xUnit test cases

How to use

Install the Nuget package.

dotnet add package Xunit.DependencyInjection

In your testing project, add the following framework

namespace Your.Test.Project
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IDependency, DependencyClass>();
        }
    }
}

Example test 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.DependencyInjection is built into the generic host and fully supports its lifecycle, allowing you to use all features supported by the generic host, including but not limited to IHostedService.

Integration asp.net core TestHost(3.0+)

Asp.Net Core Startup

dotnet add package Microsoft.AspNetCore.TestHost
public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
        .ConfigureWebHost[Defaults](webHostBuilder => webHostBuilder
        .UseTestServer(options => options.PreserveExecutionContext = true)
        .UseStartup<AspNetCoreStartup>());
}

MinimalApi

If you use MinimalApi rather than asp.net core Startup class.

Add package reference for Xunit.DependencyInjection.AspNetCoreTesting

dotnet add package Xunit.DependencyInjection.AspNetCoreTesting
public class Startup
{
    public IHostBuilder CreateHostBuilder() => MinimalApiHostBuilderFactory.GetHostBuilder<Program>();
}

Maybe your asp.net core project should InternalsVisibleTo or add public partial class Program {} in the end of Program.cs;

Detail see Xunit.DependencyInjection.Test.AspNetCore

Startup limitation

  • CreateHostBuilder method
public class Startup
{
    public IHostBuilder CreateHostBuilder([AssemblyName assemblyName]) { }
}
  • ConfigureHost method
public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) { }
}
  • ConfigureServices method
public class Startup
{
    public void ConfigureServices(IServiceCollection services[, HostBuilderContext context]) { }
}
  • Configure method

    Anything defined in ConfigureServices, can be specified in the Configure method signature. These services are injected if they're available.

How to find Startup?

1. Specific startup

Declare [Startup] on test class

2. Nested startup

public class TestClass1
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services) { }
    }

3. Closest startup

If the class type full name is "A.B.C.TestClass", find Startup in the following order:

  1. A.B.C.Startup
  2. A.B.Startup
  3. A.Startup
  4. Startup

4. Default startup

Default startup is required before 8.7.0, is optional in some case after 8.7.0.

If is required, please add a startup class in your test project.

Default is find Your.Test.Project.Startup, Your.Test.Project.

If you want to use a special Startup, you can define XunitStartupAssembly and XunitStartupFullName in the PropertyGroup section

<Project>
  <PropertyGroup>
    <XunitStartupAssembly>Abc</XunitStartupAssembly>
    <XunitStartupFullName>Xyz</XunitStartupFullName>
  </PropertyGroup>
</Project>
XunitStartupAssembly XunitStartupFullName Startup
Your.Test.Project.Startup, Your.Test.Project
Abc Abc.Startup, Abc
Xyz Xyz, Your.Test.Project
Abc Xyz Xyz, Abc

Parallel

By default, xUnit runs all test cases in a test class synchronously. This package can extend the test framework to execute tests in parallel.

<Project>

  <PropertyGroup>
    <ParallelizationMode></ParallelizationMode>
  </PropertyGroup>

</Project>

This package has two policies to run test cases in parallel.

  1. Enhance or true

    Respect xunit parallelization behavior.

  2. Force

    Ignore xunit parallelization behavior and force running tests in parallel.

If [Collection](if ParallelizationMode is not Force), [CollectionDefinition(DisableParallelization = true)], [DisableParallelization] declared on the test class, the test class will run sequentially. If [DisableParallelization], [MemberData(DisableDiscoveryEnumeration = true)] declared on the test method, the test method will run sequentially.

It is recommended to use xunit 2.8.0+ and without setting parallelAlgorithm

Thanks Meziantou.Xunit.ParallelTestFramework

How to disable Xunit.DependencyInjection

<Project>
    <PropertyGroup>
        <EnableXunitDependencyInjectionDefaultTestFrameworkAttribute>false</EnableXunitDependencyInjectionDefaultTestFrameworkAttribute>
    </PropertyGroup>
</Project>

How to inject ITestOutputHelper

internal class DependencyClass : IDependency
{
    private readonly ITestOutputHelperAccessor _testOutputHelperAccessor;

    public DependencyClass(ITestOutputHelperAccessor testOutputHelperAccessor)
    {
        _testOutputHelperAccessor = testOutputHelperAccessor;
    }
}

Write Microsoft.Extensions.Logging to ITestOutputHelper

Add package reference for Xunit.DependencyInjection.Logging

dotnet add package Xunit.DependencyInjection.Logging

The call chain must be from the test case. If not, this feature will not work.

public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services
        .AddLogging(lb => lb.AddXunitOutput());
}

How to inject IConfiguration or IHostEnvironment into Startup?

public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
        .ConfigureServices((context, services) => { context.XXXX });
}

or

public class Startup
{
    public void ConfigureServices(IServiceCollection services, HostBuilderContext context)
    {
        context.XXXX;
    }
}

How to configure IConfiguration?

public class Startup
{
    public void ConfigureHost(IHostBuilder hostBuilder) => hostBuilder
        .ConfigureHostConfiguration(builder => { })
        .ConfigureAppConfiguration((context, builder) => { });
}

[MemberData] how to inject?

Use [MethodData]

Integrate OpenTelemetry

TracerProviderBuilder builder;

builder.AddSource("Xunit.DependencyInjection");

Do something before and after test case

Inherit BeforeAfterTest and register as BeforeAfterTest service.

See demo.

Initialize some data on startup.

If it is synchronous initialization, you can use the Configure method. If it is asynchronous initialization, you should use IHostedService.

最近版本更新:(数据更新于 2024-09-12 12:25:06)

2024-05-14 09:07:59 9.3.0

2024-04-24 10:35:33 9.2.0

2024-04-04 06:24:41 9.1.0

2024-03-18 09:33:07 9.0.0

2021-11-12 21:25:42 8.2.0

2021-11-12 21:24:24 8.1.0

2021-10-21 10:33:43 8.0.0

2021-10-14 19:02:34 7.7.0

2021-09-02 23:19:15 7.6.0

2021-08-05 10:49:52 7.3.0

主题(topics):

ioc, xunit

pengweiqhca/Xunit.DependencyInjection同语言 C#最近更新仓库

2024-12-20 06:41:40 microsoft/PowerToys

2024-12-07 22:15:43 Pik-4/HsMod

2024-12-01 20:18:03 BililiveRecorder/BililiveRecorder

2024-11-26 14:48:43 Azure/azure-sdk-for-net

2024-11-19 11:38:46 jellyfin/jellyfin

2024-11-15 10:33:01 DigitalRuby/IPBan