加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:20:04 所属栏目:百科 来源:网络整理
导读:我目前正在将项目从.NET Core RC1升级到新的RTM 1.0版本.在RC1中,有一个IApplicationEnvironment在版本1.0中被IHostingEnvironment取代 在RC1我可以做到这一点 public class MyClass{ protected static IApplicationEnvironment ApplicationEnvironment { ge
我目前正在将项目从.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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读