Bil*_*ers 10 c# unit-testing .net-core asp.net-core .net-core-rc1
我目前正在将项目从.NET Core RC1升级到新的RTM 1.0版本.在RC1中,有一个在版本1.0中IApplicationEnvironment被替换IHostingEnvironment
在RC1我可以做到这一点
public class MyClass
{
protected static IApplicationEnvironment ApplicationEnvironment { get;private set; }
public MyClass()
{
ApplicationEnvironment = PlatformServices.Default.Application;
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何在v1.0中实现这一目标?
public class MyClass
{
protected static IHostingEnvironment HostingEnvironment { get;private set; }
public MyClass()
{
HostingEnvironment = ???????????;
}
}
Run Code Online (Sandbox Code Playgroud)
Nko*_*osi 13
IHostEnvironment如果需要,您可以使用模拟框架进行模拟,或者通过实现接口来创建虚假版本.
给这样的课......
public class MyClass {
protected IHostingEnvironment HostingEnvironment { get;private set; }
public MyClass(IHostingEnvironment host) {
HostingEnvironment = host;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Moq设置单元测试示例...
public void TestMyClass() {
//Arrange
var mockEnvironment = new Mock<IHostingEnvironment>();
//...Setup the mock as needed
mockEnvironment
.Setup(m => m.EnvironmentName)
.Returns("Hosting:UnitTestEnvironment");
//...other setup for mocked IHostingEnvironment...
//create your SUT and pass dependencies
var sut = new MyClass(mockEnvironment.Object);
//Act
//...call you SUT
//Assert
//...assert expectations
}
Run Code Online (Sandbox Code Playgroud)
Shi*_*mmy 13
使用Microsoft.Extensions.Hosting(它是 ASP.NET Core 中包含的包之一),您可以使用:
IHostEnvironment env =
new HostingEnvironment { EnvironmentName = Environments.Development };
Run Code Online (Sandbox Code Playgroud)
通常,由于 IHostingEnvironment 只是一个接口,您可以简单地模拟它以返回您想要的任何内容。
如果您在测试中使用 TestServer,最好的模拟方法是使用 WebHostBuilder.Configure 方法。像这样的东西:
var testHostingEnvironment = new MockHostingEnvironment();
var builder = new WebHostBuilder()
.Configure(app => { })
.ConfigureServices(services =>
{
services.TryAddSingleton<IHostingEnvironment>(testHostingEnvironment);
});
var server = new TestServer(builder);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9024 次 |
| 最近记录: |