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

前端之家收集整理的这篇文章主要介绍了c# – 在单元测试中设置IHostingEnvironment前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在将项目从.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
}

猜你在找的C#相关文章