我目前正在将项目从.NET Core RC1升级到新的RTM 1.0版本。在RC1中,有一个IApplicationEnvironment
,在1.0版中被IHostingEnvironment
取代
在RC1中,我可以这样做
public class MyClass
{
protected static IApplicationEnvironment ApplicationEnvironment { get;private set; }
public MyClass()
{
ApplicationEnvironment = PlatformServices.Default.Application;
}
}
有谁知道如何在v1.0中实现这一目标?
public class MyClass
{
protected static IHostingEnvironment HostingEnvironment { get;private set; }
public MyClass()
{
HostingEnvironment = ???????????;
}
}
最佳答案
您可以根据需要使用模拟框架模拟IHostEnvironment
,也可以通过实现接口(interface)来创建伪造的版本。
像这样上课...
public class MyClass {
protected IHostingEnvironment HostingEnvironment { get;private set; }
public MyClass(IHostingEnvironment host) {
HostingEnvironment = host;
}
}
您可以使用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
}