And*_*aal 1 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.
Run Code Online (Sandbox Code Playgroud)
我的核心模块的构造函数:
public imfundoplatformCoreModule(IHostingEnvironment env)
{
_appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何将它传递给模块或让单元测试正常工作。请帮忙!
您可以注入 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();
}
}
Run Code Online (Sandbox Code Playgroud)
之后,将此添加到您Initialize()的 TestModule 中:
public override void Initialize()
{
(...)
IocManager.Register<IHostingEnvironment, MockHostingEnvironment>(DependencyLifeStyle.Singleton);
}
Run Code Online (Sandbox Code Playgroud)
请注意,使用 Environment.CurrentDirectory 是一种非常糟糕的方式。它可能指向不同的目录,具体取决于您的 CI、您的测试运行程序、您的测试框架等。
如果您在测试中使用需要 IHostingEnvironment 的服务,您应该只使用此 MockHostingEnvironment。
| 归档时间: |
|
| 查看次数: |
3942 次 |
| 最近记录: |