c# – 在单元测试中设置IHostingEnvironment

前端之家收集整理的这篇文章主要介绍了c# – 在单元测试中设置IHostingEnvironment前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在将项目从.NET Core RC1升级到新的RTM 1.0版本.在RC1中,有一个IApplicationEnvironment在版本1.0中被IHostingEnvironment取代

在RC1我可以做到这一点

  1. public class MyClass
  2. {
  3. protected static IApplicationEnvironment ApplicationEnvironment { get;private set; }
  4.  
  5. public MyClass()
  6. {
  7. ApplicationEnvironment = PlatformServices.Default.Application;
  8. }
  9. }

有谁知道如何在v1.0中实现这一目标?

  1. public class MyClass
  2. {
  3. protected static IHostingEnvironment HostingEnvironment { get;private set; }
  4.  
  5. public MyClass()
  6. {
  7. HostingEnvironment = ???????????;
  8. }
  9. }

解决方法

如果需要,您可以使用模拟框架模拟IHostEnvironment,或者通过实现接口创建虚假版本.

给这样的课……

  1. public class MyClass {
  2. protected IHostingEnvironment HostingEnvironment { get;private set; }
  3.  
  4. public MyClass(IHostingEnvironment host) {
  5. HostingEnvironment = host;
  6. }
  7. }

您可以使用Moq设置单元测试示例…

  1. public void TestMyClass() {
  2. //Arrange
  3. var mockEnvironment = new Mock<IHostingEnvironment>();
  4. //...Setup the mock as needed
  5. mockEnvironment
  6. .Setup(m => m.EnvironmentName)
  7. .Returns("Hosting:UnitTestEnvironment");
  8. //...other setup for mocked IHostingEnvironment...
  9.  
  10. //create your SUT and pass dependencies
  11. var sut = new MyClass(mockEnvironment.Object);
  12.  
  13. //Act
  14. //...call you SUT
  15.  
  16. //Assert
  17. //...assert expectations
  18. }

猜你在找的C#相关文章