简体   繁体   English

IHostingEnvironment进行测试

[英]IHostingEnvironment for testing

I'm trying to use the unit test project in ABP 2.0.2 and I get the following error when I run the selected test GetUsers_Test() . 我试图在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.

The constructor for my Core module: 我的Core模块的构造函数:

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

I cannot figure out how to pass this to the module or get unit tests working. 我不知道如何将其传递给模块或使单元测试正常工作。 Please help! 请帮忙!

You can inject IHostingEnvironment. 可以注入IHostingEnvironment。 But you will have to do it in some weird ways: 但是您将不得不以一些奇怪的方式来做:

First create a mock IHostingEnvrionment class like this (adjust it to your needs): 首先像这样创建一个模拟的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();
    }
}

After that add this to your Initialize() of your TestModule: 之后,将其添加到您的TestModule的Initialize()中:

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

Note that using Environment.CurrentDirectory is a very bad way of doing it. 请注意,使用Environment.CurrentDirectory是一种非常糟糕的方法。 It might point to a different directory depending on your CI, your test runner, your testing framework etc. 根据您的配置项,测试运行程序,测试框架等,它可能指向不同的目录。

You should only use this MockHostingEnvironment if you use services in your test which need the IHostingEnvironment. 如果在测试中使用需要IHostingEnvironment的服务,则应使用此MockHostingEnvironment。

您不能注入IHostingEnvironment ...要获取内容的根路径,请使用;

Directory.GetCurrentDirectory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM