IHostingEnvironment用于测试

时间:2017-12-06 12:23:32

标签: 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.

Core 模块的构造函数:

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

我无法弄清楚如何将其传递给模块或让单元测试工作。请帮忙!

2 个答案:

答案 0 :(得分:2)

你无法注入 IHostingEnvironment ...要使用内容根路径;

Directory.GetCurrentDirectory

答案 1 :(得分:1)

可以注入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。