如何对startup.cs .Net Core进行单元测试

时间:2018-11-23 14:04:58

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

我的帖子是帖子How to Unit Test Startup.cs in .NET Core的扩展

我尝试使用此代码(与上一篇文章相同的代码)对Startup.ca类进行单元测试:

[TestMethod]
public void ConfigureServices_RegistersDependenciesCorrectly()
{
    //  Arrange

    //  Setting up the stuff required for Configuration.GetConnectionString("DefaultConnection")
    Mock<IConfigurationSection> configurationSectionStub = new Mock<IConfigurationSection>();
    configurationSectionStub.Setup(x => x["DefaultConnection"]).Returns("TestConnectionString");
    Mock<Microsoft.Extensions.Configuration.IConfiguration> configurationStub = new Mock<Microsoft.Extensions.Configuration.IConfiguration>();
    configurationStub.Setup(x => x.GetSection("ConnectionStrings")).Returns(configurationSectionStub.Object);

    IServiceCollection services = new ServiceCollection();
    var target = new Startup(configurationStub.Object);

    //  Act    
    target.ConfigureServices(services);
    //  Mimic internal asp.net core logic.
    services.AddTransient<TestController>();

    //  Assert    
    var serviceProvider = services.BuildServiceProvider();

    var controller = serviceProvider.GetService<TestController>();
    Assert.IsNotNull(controller);
}

但是我在target.ConfigureServices(services)行出现了错误。当我运行测试时。我收到了错误:

  

消息:测试方法Project.Services.PublicReporting.Tests.StartupTests.ConfigureServices_RegistersDependencies正确抛出异常:       System.IO.FileLoadException:无法加载文件或程序集“ Microsoft.Extensions.Caching.Memory,版本= 2.1.2.0,区域性=中性,PublicKeyToken = adb9793829ddae60”或其依赖项之一。找到的程序集的清单定义与程序集引用不匹配。 (来自HRESULT的异常:0x80131040)---> System.IO.FileLoadException:无法加载文件或程序集“ Microsoft.Extensions.Caching.Memory,版本= 2.1.1.0,Culture = neutral,PublicKeyToken = adb9793829ddae60”或其中之一依赖性。找到的程序集的清单定义与程序集引用不匹配。 (来自HRESULT的异常:0x80131040)

这是因为我们正在调用ConfigureService,并且它在services.AddResponseCaching();上崩溃

这是我的Configures Service方法,它在第二行崩溃。

public void ConfigureServices(IServiceCollection services)
        {
            services.RegisterApplicationComponents();

            services.AddResponseCaching();
}

我认为问题在于,当我们模拟该类时,我无法找到我们需要具有哪个正确的设置,以便AddResponseCaching()方法能够通过。是否有人知道configurationSectionStub.Setup中缺少的内容,还是我们需要模拟服务的行为?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用Integration tests in ASP.NET Core来确保Startup基础架构正常运行。请注意,您可以通过在主机构建器上使用ConfigureTestServices在测试中覆盖treal服务来注入模拟服务。

[Fact]
public async Task Get_QuoteService_ProvidesQuoteInPage()
{
    // Arrange
    var client = _factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddScoped<IQuoteService, TestQuoteService>();
            });
        })
        .CreateClient();

    //Act
    var defaultPage = await client.GetAsync("/");
    var content = await HtmlHelpers.GetDocumentAsync(defaultPage);
    var quoteElement = content.QuerySelector("#quote");

    // Assert
    Assert.Equal("Something's interfering with time, Mr. Scarman, " +
        "and time is my business.", quoteElement.Attributes["value"].Value);
}