Unit testing an AuthorizeAttribute on an ASP.NET Core MVC API controller

前端 未结 2 1509
再見小時候
再見小時候 2021-01-01 21:43

I have a ASP.NET Core MVC API with controllers that need to be unit tested.

Controller:

using Microsoft.AspNetCore.Authorization;
u         


        
相关标签:
2条回答
  • 2021-01-01 22:15

    This would need integration testing with an in-memory test server because the attribute is evaluated by the framework as it processes the request pipeline.

    Integration testing in ASP.NET Core

    Integration testing ensures that an application's components function correctly when assembled together. ASP.NET Core supports integration testing using unit test frameworks and a built-in test web host that can be used to handle requests without network overhead.

    [Fact]
    public async Task GetAsync_InvalidScope_ReturnsUnauthorizedResult() {
        // Arrange
        var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
        var client = server.CreateClient();
        var url = "api/foo";
        var expected = HttpStatusCode.Unauthorized;
    
        // Act
        var response = await client.GetAsync(url);
    
        // Assert
        Assert.AreEqual(expected, response.StatusCode);
    }
    

    You can also create a start up specifically for the test that will replace any dependencies for DI with stubs/mocks if you do not want the test hitting actual production implementations.

    0 讨论(0)
  • 2021-01-01 22:23

    What you could do, is to configure your testserver to add an anonymous filter middleware:

    private HttpClient CreatControllerClient()
    {
            return _factory.WithWebHostBuilder(builder
                => builder.ConfigureTestServices(services =>
                {
                    // allow anonymous access to bypass authorization
                    services.AddMvc(opt => opt.Filters.Add(new AllowAnonymousFilter()));
                })).CreateClient();
    }
    
    0 讨论(0)
提交回复
热议问题