首页 > 解决方案 > Asp .Net Core 3.0 在测试中添加自定义 Startup 类会导致不再提供视图

问题描述

我正在测试一个 Asp .Net Core 3.0 MVC 应用程序。这是一个使用命令创建的基本示例应用程序dotnet new mvc。在 xunit 测试项目中,我正在测试IndexHomeController. 测试看起来像这样:

public class HomeControllerTests
{
    [Fact]
    public async Task ReturnsView()
    {
        const string testProjectDir = "ViewsTestingTests";
        var factory = new TestServerFactory();
        var client = factory.WithWebHostBuilder(builder =>
        {
            builder.UseSolutionRelativeContentRoot(testProjectDir);
            builder.ConfigureTestServices(services =>
            {
                services.AddControllersWithViews()
                    .AddApplicationPart(typeof(Startup).Assembly);
            });
        }).CreateClient();

        var resultIndex = await client.GetAsync("/");
        resultIndex.StatusCode.Should().Be(200);
        var content = await resultIndex.Content.ReadAsStringAsync();
        content.Should().Contain("Welcome");
    }
}

public class TestServerFactory : WebApplicationFactory<TestStartup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder(null)
            .UseStartup<TestStartup>();
    }
}

public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration) : base(configuration)
    {
    }
}

我正在使用一个测试启动类,因为我将覆盖一些方法。当我使用这个TestStartup类时,测试没有通过。原因如下:

The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml

但是,如果我像这样使用主项目中的 Startup 类:

public class TestServerFactory : WebApplicationFactory<Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder(null)
            .UseStartup<Startup>();
    }
}

并像这样创建客户端:

var client = factory.WithWebHostBuilder(builder =>
            {
                builder.UseSolutionRelativeContentRoot(testProjectDir);
            }).CreateClient();

然后测试通过。当然,我将整个 Views 文件夹复制到了测试项目中。

解决方案结构。视图在测试项目中

有趣的是,以前在 Asp 中工作的相同测试。网络核心 2.2。builder.UseContentRoot在内部使用factory.WithWebHostBuilder并设置测试项目文件夹的路径无济于事。请帮助我如何解决这个问题。

标签: c#asp.net-core

解决方案


推荐阅读