using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;

namespace Dzp.Core.XunitBasic;

public abstract class Basic
{
    private IServiceProvider? _serviceProvider;
    private readonly IServiceCollection _services;

    protected Basic(ITestOutputHelper testOutputHelper)
    {
        var config = new ConfigurationBuilder().AddJsonFile("appsettings.Test.json").Build();
        Configuration = config;
        _services = new ServiceCollection();
        _services.AddSingleton<IConfiguration>(_ => config);
        _services.AddSingleton<HttpClient>(_ => new HttpClient());

        _services.AddLogging(builder =>
        {
            builder.AddConfiguration(config);
            builder
                .AddFilter(null, LogLevel.Debug)
                .AddProvider(new XunitLoggerProvider(testOutputHelper));
        });
    }

    protected IServiceProvider ServiceProvider =>
        _serviceProvider ?? throw new Exception("ServiceProvider is null");

    protected IConfiguration Configuration { get; }

    private bool _isBuild;

    protected void BuildService(Action<IServiceCollection>? servicesAction = null)
    {
        if (_isBuild)
        {
            return;
        }

        servicesAction?.Invoke(_services);
        _serviceProvider = _services.BuildServiceProvider();
        _isBuild = true;
    }

    protected void ConfigureServices(Action<IServiceCollection> servicesAction)
    {
        if (_isBuild)
        {
            return;
        }

        servicesAction(_services);
    }

    protected T GetService<T>()
    {
        return ServiceProvider.GetService<T>()
            ?? throw new Exception(
                $"service {typeof(T).Name} is null,please use method BuildService"
            );
    }
}
⚠⚠    以下内容为AI分析的结果,请根据实际情况进行判断。

这是一个用于xUnit单元测试的抽象基类,提供了依赖注入容器和配置管理的基础设施。让我详细解释一下:

类的用途

Basic 是一个抽象基类,专门为 xUnit 测试项目设计,提供了标准化的服务容器配置和依赖注入功能。

主要组件

1. 构造函数

protected Basic(ITestOutputHelper testOutputHelper)
  • 接收 xUnit 的 ITestOutputHelper 用于测试输出
  • 自动加载 appsettings.Test.json 配置文件
  • 预配置了基础服务:
    • IConfiguration: 配置服务
    • HttpClient: HTTP客户端
    • 日志系统:集成了 xUnit 的输出机制

2. 核心属性

  • ServiceProvider: 获取构建后的服务提供者
  • Configuration: 访问配置信息
  • _isBuild: 防止重复构建的标志

3. 主要方法

BuildService(Action<IServiceCollection>? servicesAction = null)

  • 构建服务容器
  • 可选择性地传入额外的服务配置
  • 使用防重复构建机制

ConfigureServices(Action<IServiceCollection> servicesAction)

  • 在构建前配置额外服务
  • 如果已构建则忽略配置

GetService<T>()

  • 泛型方法获取注册的服务
  • 包含空值检查和友好的错误提示

使用示例

public class MyTest : Basic
{
    public MyTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
    {
        // 配置测试特有的服务
        ConfigureServices(services =>
        {
            services.AddScoped<IMyService, MyService>();
        });
        
        // 构建服务容器
        BuildService();
    }

    [Fact]
    public void TestMethod()
    {
        // 获取服务进行测试
        var myService = GetService<IMyService>();
        // 测试逻辑...
    }
}

设计优点

  1. 标准化: 为所有测试类提供一致的基础设施
  2. 灵活性: 允许子类自定义服务配置
  3. 安全性: 包含完善的空值检查和错误处理
  4. 集成性: 与 xUnit 测试框架深度集成,支持测试输出

这个基类很好地封装了测试项目中常见的依赖注入需求,让测试代码更加简洁和可维护。

评论加载中...