Skip to content

Ammending the request pipeline with WebApplicationFactory #3254

@chris-brown

Description

@chris-brown

dotnet/AspNetCore.Docs#7203

Im trying to create a integration test for my Exception handling middleware How do you add to the existing ApplicationBuilder with WebApplicationFactory?

Im using WebApplicationFactory<T> with my Startup.cs and I want to add an additional middleware to the request pipeline so I can mimic a error response.

The example below completely overrides my Startup which is not the desired result. I noticed builder has the following extension methods ConfigureTestServices() and ConfigureTestContainer() but there doesnt appear to be an equivilant to configure the request pipeline thats under test.

_client = fixture.WithWebHostBuilder(builder =>
{
   builder.Configure(app =>
   {
      app.Map("/error", a => a.Run(c => throw new Exception("My error message")));
   });
}).CreateDefaultClient();

Perhaps I could use a IStartupFilter which throws at the end of the request pipeline. But im not sure how I could get that to invoke after my middleware.

This seems to do it but its alot of boiler plate. I'm hoping im missing something obvious.

    public class ErrorsController : Controller
    {
        [Route("Error")]
        public IActionResult Error() => throw new Exception();
    }

    public class ExceptionMiddlewareTests : IClassFixture<WebApplicationFactory<Startup>>
    {
        private readonly HttpClient _client;

        public ExceptionMiddlewareTests(WebApplicationFactory<Startup> fixture)
        {
            _client = fixture.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(collection =>
                {
                    var mvc = collection.AddMvc();
                    var parts = mvc.PartManager.ApplicationParts;
                    parts.Clear();
                    parts.Add(new AssemblyPart(typeof(Startup).GetTypeInfo().Assembly));
                    parts.Add(new AssemblyPart(GetType().Assembly));
                });
            }).CreateDefaultClient();
        }
        // ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions