简体   繁体   中英

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() .

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:

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. But you will have to do it in some weird ways:

First create a mock IHostingEnvrionment class like this (adjust it to your needs):

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:

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

Note that using Environment.CurrentDirectory is a very bad way of doing it. 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 ...要获取内容的根路径,请使用;

Directory.GetCurrentDirectory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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