c# - 用于测试的 IHostingEnvironment

标签 c# aspnetboilerplate

我正在尝试使用 ABP 2.0.2 中的单元测试项目,但在运行所选测试 GetUsers_Test() 时出现以下错误。

Message: Castle.MicroKernel.Handlers.HandlerException : Can't create component 'imfundoplatform.imfundoplatformCoreModule' as it has dependencies to be satisfied.

'imfundoplatform.imfundoplatformCoreModule' is waiting for the following dependencies:
- Service 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' which was not registered.

我的核心模块的构造函数:

public imfundoplatformCoreModule(IHostingEnvironment env)
{
    _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
}

我不知道如何将它传递给模块或让单元测试正常工作。请帮忙!

最佳答案

可以注入(inject) IHostingEnvironment。但是你必须以一些奇怪的方式来做:

首先像这样创建一个模拟的 IHostingEnvrionment 类(根据您的需要进行调整):

public class MockHostingEnvironment : IHostingEnvironment, ISingletonDependency
{
    public string EnvironmentName
    {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }

    public string ApplicationName
    {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }
    public string WebRootPath { get; set; } = Path.Combine(Environment.CurrentDirectory, "wwwroot");
    public IFileProvider WebRootFileProvider
    {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }

    public string ContentRootPath { get; set; } = Environment.CurrentDirectory;

    public IFileProvider ContentRootFileProvider
    {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }
}

之后将其添加到您的 TestModule 的 Initialize() 中:

public override void Initialize()
{
    (...)
    IocManager.Register<IHostingEnvironment, MockHostingEnvironment>(DependencyLifeStyle.Singleton);
}

请注意,使用 Environment.CurrentDirectory 是一种非常糟糕的做法。它可能指向不同的目录,具体取决于您的 CI、测试运行器、测试框架等。

如果您在测试中使用需要 IHostingEnvironment 的服务,您应该使用此 MockHostingEnvironment。

关于c# - 用于测试的 IHostingEnvironment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47674237/

相关文章:

asp.net - 类型 'Object' 在未引用的程序集中定义

c# - EF Core 日期时间偏移

c# - StringCollection.Count 意外增加

c# - 从数据读取器填充数据表

c# - 添加整个文件夹(带有子文件夹)作为嵌入式资源?

c# - ASPNETBOILERPLATE - 应用程序服务方法不返回 .NET Core 中的相关实体

c# - 如何从 PDF 中提取文本并解码字符?

aspnetboilerplate - ABP 中的 System.ObjectDisposeException

c# - ASP.NET 样板 .NET Core 2

AspNetBoilerplate 不从数据库加载设置