NetCore Xunit单元测试依赖注入
1.添加Nuget: Xunit.DependencyInjection
install-package Xunit.DependencyInjection -project CustProjectName
2.Xunit项目根目录添加文件: Startup.cs
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; /// <summary> /// Xunit.DependencyInjection 7.3.0 /// </summary> namespace CoreXUnitTestProject { // Startup 需要继承于 DependencyInjectionTestFramework public class Startup { // 自定义 host 构建 public void ConfigureHost(IHostBuilder hostBuilder) { //hostBuilder.ConfigureAppConfiguration(builder => //{ // // 注册配置 // builder.AddInMemoryCollection(new Dictionary<string, string>() // { // {"UserName", "Alice"} // }).AddJsonFile("appsettings.json"); //}) //.ConfigureServices((context, services) => //{ // // 注册自定义服务 // services.AddSingleton<IIdGenerator, GuidIdGenerator>(); // if (context.Configuration.GetAppSetting<bool>("XxxEnabled")) // { // services.AddSingleton<IUserIdProvider, EnvironmentUserIdProvider>(); // } //}); } /// <summary> /// /// 支持的形式: /// ConfigureServices(IServiceCollection services) /// ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext) /// ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services) /// </summary> /// <param name="services"></param> /// <param name="hostBuilderContext"></param> public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext) { services.AddTransient<ITestService, TestService>(); } /// <summary> /// 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法 /// </summary> /// <param name="provider"></param> public void Configure(IServiceProvider provider) { } } }
2.1.如果需要注入泛型
services.AddSingleton<XxxDo>(); services.AddSingleton<XxxDto>(); // services.AddTransient(typeof(IBaseDal<XxxDo, XxxDto>), typeof(MemoryBaseDal<XxxDo, XxxDto>)); services.AddTransient(typeof(IBaseDal<,>), typeof(MemoryBaseDal<,>));
3.使用和CoreWebApi一样,正常注入
public class TestAutofac : BaseTesting { public readonly ITestService _testService; public TestAutofac(ITestOutputHelper testOutputHelper, ITestService testService) : base(testOutputHelper) { _testService = testService; } [Fact] public void TestRun() { var result = _testService.Run(); _testOutputHelper.WriteLine(result); } }
Reference:
https://www.cnblogs.com/weihanli/p/13941796.html
https://blog.csdn.net/sD7O95O/article/details/107437559