[英]Why the TestServer (AspNetCore) gives 404 error on static files?
I have a sample server我有一个示例服务器
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
with configuration in Startup class:在启动类中配置:
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
and I am using xunit test (learning):我正在使用 xunit 测试(学习):
public TestFixture()
{
var builder = new WebHostBuilder().UseStartup<TStartup>();
_server = new TestServer(builder);
Client = _server.CreateClient();
Client.BaseAddress = new Uri(address);
}
and later后来
var response = await Client.GetAsync("http://localhost:51021/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var responseString = await response.Content.ReadAsStringAsync();
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("Hello World!", content);
Everything is OK (200).一切正常(200)。 Now I am changing Startup.cs
现在我正在更改 Startup.cs
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
}
If I start the app with browser, everything is OK (index.html shown).如果我用浏览器启动应用程序,一切正常(显示 index.html)。 But if I call it with the TestServer I receive (404 Not found).
但是如果我用 TestServer 调用它,我会收到(404 Not found)。 Where is my error?
我的错误在哪里?
XUnit starts the site from a different directory. XUnit 从不同的目录启动站点。 We've had to work around it like this: https://github.com/aspnet/StaticFiles/blob/d692066b2bd711653150ad2cccc2268583355532/test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.cs#L20
我们不得不像这样解决它: https : //github.com/aspnet/StaticFiles/blob/d692066b2bd711653150ad2cccc2268583355532/test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.cs#L20
Another approach is to copy those files into your unit test project另一种方法是将这些文件复制到您的单元测试项目中
Then然后
As far as you maintain the same structure folder of the project that you are testing, it will find out the files and pass it to the dependency injection process.只要您维护与您正在测试的项目相同的结构文件夹,它就会找出文件并将其传递给依赖注入过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.