我目前正在将项目从.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,或者通过实现接口创建虚假版本.
给这样的课……
- 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
- }