我正在尝试使用 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/