c# - Asp .Net Core 3.0 在测试中添加自定义 Startup 类会导致不再提供视图
问题描述
我正在测试一个 Asp .Net Core 3.0 MVC 应用程序。这是一个使用命令创建的基本示例应用程序dotnet new mvc
。在 xunit 测试项目中,我正在测试Index
从HomeController
. 测试看起来像这样:
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
并设置测试项目文件夹的路径无济于事。请帮助我如何解决这个问题。
解决方案
推荐阅读
- testng - 如何将 TestNGReporter 添加到 Log4j 2.x?
- symfony - Symfony RedisAdapter 根据应用环境有不同的内部缓存键
- c++ - 编译使用 Open Dynamics Engine v0.13.1 的文件时出现“对 * 的未定义引用”错误
- mysql - 如何测试一个 id 列表是否存在于另一个 id 列表中?
- java - 如何将模块包含在另一个项目的顶级 POM 中?
- python - 使用 np.where 循环
- javascript - Firebase 身份验证需要两次“登录”调用
- mysql - mysql触发一对多关系
- angular - Angular 中的 CORS 策略已阻止访问 XMLHttpRequest
- javascript - While 循环仅在 draw() 函数 (P5.js) (P5.play) 中运行一次