Skip to content

WebApplicationFactory - Exception not being caught by HttpClient #19217

@D3niz

Description

@D3niz

Describe the bug

When using WebApplicationFactory, and using CreateHostBuilder to set it up, Then in a test HttpClient from _factory.CreateClient() is used to call an endpoint and that endpoint method has an exception within its code and the HttpClient should catch that exception and a bad request StatusCode is expected, what is happening though is the exception is bubbling up to the test and the test fails from whatever the exception is during the endpoint method and no response is ever returned from the client.

This is only the case when using CreateHostBuilder(), if using something like ConfigureWebHost() then it works fine and a bad request response from the client is returned as expected.

To Reproduce

A test base class with

private class WeatherForecastApplicationFactory : WebApplicationFactory<Startup>
{
    protected override IHostBuilder CreateHostBuilder() =>
        Host.CreateDefaultBuilder()
            .ConfigureWebHost(w => w.UseStartup<Startup>());
}

Then in a unit test
var response = await Client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/api/test"));

And then the method that it is calling, just throw an exception
e.g.

[HttpGet]
public IActionResult Get()
{
    throw new Exception();
}

Further technical details

netcoreapp3.1
Microsoft.AspNetCore.Mvc.Testing: 3.15.1
nunit: 3.12.0
NUnit3TestAdapter: 3.15.1
Microsoft.NET.Test.Sdk: 16.4.0

Microsoft Visual Studio Professional 2019
Version 16.4.5
ReSharper Ultimate 2019.3.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions