在单元测试中设置IHostingEnvironment

本文关键字:IHostingEnvironment 设置 单元测试 | 更新日期: 2023-09-27 17:54:06

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

在单元测试中设置IHostingEnvironment

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

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

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

一般来说,由于IHostingEnvironment只是一个接口,您可以简单地模拟它以返回您想要的任何内容。

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

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

我们在测试中是这样做的:

     var serviceProvider =  new ServiceCollection()
        .AddScoped<IHostingEnvironment, MockHostingEnvironment>()
        .AddScoped<IAccessPointService, AccessPointService>()
          .BuildServiceProvider();

MockHosting的定义,您可以更改实现以满足您的需求:

 public class MockHostingEnvironment : IHostingEnvironment
{
    public string EnvironmentName { get => return "Testing"; set => throw new NotImplementedException(); }
    public string ApplicationName { get => "My App"; set => throw new NotImplementedException(); }
    public string ContentRootPath { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public IFileProvider ContentRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}

最后,我们只需向服务提供者询问需要DI的类的实例:

    var accessPointService = serviceProvider.GetService<IAccessPointService>();     
相关文章:
  • 没有找到相关文章