且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 ASP.NET Core MVC API 控制器上对 AuthorizeAttribute 进行单元测试

更新时间:2023-02-17 08:03:07

这需要使用内存测试服务器进行集成测试,因为框架在处理请求管道时会评估该属性.

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.

ASP.NET Core 中的集成测试

集成测试可确保应用程序的组件在组装在一起时正常运行.ASP.NET Core 支持使用单元测试框架和内置测试 Web 主机进行集成测试,该主机可用于处理请求而无需网络开销.

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);
}

如果您不希望测试影响实际的生产实现,您还可以专门为测试创建一个启动项,用存根/模拟替换 DI 的任何依赖项.

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.