在单元测试中设置IHostingEnvironment

时间:2016-07-01 00:59:51

标签: c# unit-testing asp.net-core .net-core-rc1

我目前正在将项目从.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 = ???????????;
    }
}

3 个答案:

答案 0 :(得分:12)

如果需要,您可以使用模拟框架模拟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
}

答案 1 :(得分:5)

使用Microsoft.Extensions.Hosting(ASP.NET Core中包含的软件包之一),您可以使用:

IHostEnvironment env = 
    new HostingEnvironment { EnvironmentName = Environments.Development };

答案 2 :(得分:2)

一般来说,由于IHostingEnvironment只是一个界面,你可以简单地模仿它来返回你想要的任何东西。

如果您在测试中使用TestServer,最好的模拟方法是使用WebHostBuilder.Configure方法。像这样:

var testHostingEnvironment = new MockHostingEnvironment(); 
var builder = new WebHostBuilder()
            .Configure(app => { })
            .ConfigureServices(services =>
            {
                services.TryAddSingleton<IHostingEnvironment>(testHostingEnvironment);
            });
var server = new TestServer(builder);