Venator
Venator

Reputation: 352

C# integration test status "not run" when authorization returns forbidden

I am currently writing C# integration tests for an ASP.NET Core project. I want to have tests that validate endpoint security - specifically, that the endpoint grants access to an authorised user, but denies access to an unauthorised user. I've got a working test for the first use case, but I've run into some odd behaviour on the second.

Here is the integration test:

        [Test]
    public async Task GetDrives_ShouldReturnForbidden_WhenCalledByExternalUser()
    {
        // Arrange
        TestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test", "[email protected]");
        UriBuilder builder = new("https://localhost/api/Drive");
        builder.Query = "Id=49";
        // Act
        HttpResponseMessage response = await TestClient.GetAsync(builder.Uri);
        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
        // Assert
        response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
        responseContent.ShouldBeEmpty();
    }

Now, the test does exactly what its name says - the endpoint returns forbidden. Where the behaviour gets odd is that when I run this test, I would expect it to pass, but instead, it results in a "not run" status. When debugging the test, I can see that it runs all the way through, so the test does run, but the final status doesn't reflect that.

After much googling, I haven't found anything that explains this behaviour. My suspicion is that this is in part because the request is processed by an [Authorize] attribute, so it never hits the endpoint code, which the test framework knows, thus deeming the test "not run". Has anyone encountered this before and can confirm that this is what's happening? And does anyone know how to make this test produce a pass/fail result?

Upvotes: 1

Views: 864

Answers (1)

Venator
Venator

Reputation: 352

Troubleshooting a similar testing issue (a test that wasn't being consistently rerun) helped me discover the answer.

The cause of both issues was an exception being thrown by the console.writeline, but the IDE wasn't actively flagging it, only logging it, therefore somewhat obscuring the issue from view.

The writeline value parameter was only whitespace when the endpoint call was forbidden, causing a System.ArgumentException: The parameter cannot be null or empty. A small tweak to the code prevents the exception from occurring and provides a correct pass result.

Here was the code before:

enter image description here

And here was the code afterwards:

enter image description here

The takeaway here - if running tests in visual studio, and you're getting odd behaviour like tests that run but don't provide an outcome, or tests that ran once but don't on a rerun, check the test runner output - there may be errors hiding away there!

Upvotes: 2

Related Questions