Why the TestServer (AspNetCore) gives 404 error on static files?
Asked Answered
T

2

1

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):

        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). Now I am changing 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). But if I call it with the TestServer I receive (404 Not found). Where is my error?

Toney answered 14/6, 2016 at 14:45 Comment(0)
P
2

XUnit starts the site from a different directory. We've had to work around it like this: https://github.com/aspnet/StaticFiles/blob/d692066b2bd711653150ad2cccc2268583355532/test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.cs#L20

Protagonist answered 14/6, 2016 at 16:39 Comment(0)
L
0

Another approach is to copy those files into your unit test project

enter image description here

Then

enter image description here

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.

Lewes answered 18/6, 2020 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.