在单元测试中设置IHostingEnvironment

Bil*_*ers 10 c# unit-testing .net-core asp.net-core .net-core-rc1

我目前正在将项目从.NET Core RC1升级到新的RTM 1.0版本.在RC1中,有一个在版本1.0中IApplicationEnvironment被替换IHostingEnvironment

在RC1我可以做到这一点

public class MyClass
{
    protected static IApplicationEnvironment ApplicationEnvironment { get;private set; }

    public MyClass()
    {
        ApplicationEnvironment = PlatformServices.Default.Application;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public class MyClass
{
    protected static IHostingEnvironment HostingEnvironment { get;private set; }

    public MyClass()
    {
        HostingEnvironment = ???????????;
    }
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 13

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

给这样的课......

public class MyClass {
    protected IHostingEnvironment HostingEnvironment { get;private set; }

    public MyClass(IHostingEnvironment host) {
        HostingEnvironment = host;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

  • @user1785960 为什么需要设置它?如果将模拟对象的“EnvironmentName”设置为“Development”,则“IsDevelopment”扩展方法将返回“true”。至少就我而言,这就是我所需要的。 (3认同)

Shi*_*mmy 13

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

IHostEnvironment env = 
    new HostingEnvironment { EnvironmentName = Environments.Development };
Run Code Online (Sandbox Code Playgroud)


Set*_*Set 6

通常,由于 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);
Run Code Online (Sandbox Code Playgroud)

  • 我不想使用 TestServer 类。我相信这更多用于集成测试。我不需要启动应用程序的完整实例。我只想测试一个特定的类。我有一个 Test 基类,它在 RC1 中使用了“ApplicationEnvironment”,但我似乎无法在 1.0 中轻松替换它 (2认同)