I am learning to do integration testing with MSTest with .NET 8.

To that end, I've written some simple API endpoints to test against. I tried writing tests that check that I can send GET and POST requests to an endpoint that simply returns HTTP 200, and this worked well for me.

I ran into trouble when I tried to write a test that would hit an endpoint that I had rigged up to throw an uncaught exception. I expected that it should return HTTP 500, but I found that the HttpClient object rethrows the exception.

I had the idea that in the integration test, the framework would spin up an instance of Kestrel and hit it with an actual HTTP request, but it looks like that's not exactly what happens. I noticed that nothing gets caught by Fiddler, for example.

Here is my test code:

[TestMethod()]
public async Task GetOrangesTest()
{
    try
    {
        var httpResponse = await HttpClient.GetAsync("api/orange");
        // Flow jumps to the catch block before the next line runs.
        var result = httpResponse.IsSuccessStatusCode;
        Assert.IsFalse(result);
    }
    catch (Exception ex)
    {
        // Here, I have the stacktrace from the API endpoint.
        // I expect that the API endpoint should have returned HTTP 500.
    }
}

Why is my test behaving this way?

How do I test that my API endpoint returns HTTP 500?

0

There are 0 best solutions below