且构网

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

如何编写针对ASP.NET Web API的集成测试

更新时间:2021-12-13 23:17:59

在ASP.NET Web API中,身份验证发生在调用Controllers之前的管道中,因此您需要为此编写一些集成测试.我会在外部TDD 的在线课程中指导您完成该操作,但是这是要点:

In ASP.NET Web API, Authentication happens in the pipeline before the Controllers are invoked, so you'll need to write some Integration Tests for that. I walk you through how to do that in my on-line course on Outside-In TDD, but here's the gist of it:

这是使用内存HTTP 请求针对资源进行的集成测试.此测试不使用网络:

Here's an Integration Test against a resource using in-memory HTTP requests. This test doesn't use the network:

[Fact]
public void GetReturnsResponseWithCorrectStatusCode()
{
    var baseAddress = new Uri("http://localhost:8765");
    var config = new HttpSelfHostConfiguration(baseAddress);
    config.Routes.MapHttpRoute(
        name: "API Default",
        routeTemplate: "{controller}/{id}",
        defaults: new
        {
            controller = "Home",
            id = RouteParameter.Optional
        });
    var server = new HttpSelfHostServer(config);
    using (var client = new HttpClient(server))
    {
        client.BaseAddress = baseAddress;
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue(
                "Bearer",
                new SimpleWebToken(new Claim("userName", "foo")).ToString());

        var response = client.GetAsync("").Result;

        Assert.True(
            response.IsSuccessStatusCode,
            "Actual status code: " + response.StatusCode);
    }
}

如您所见,它将"Bearer"令牌添加到请求的HTTP标头中. SimpleWebToken类只是我为此编写的一个自定义类,但是您可以将其替换为一个更好的类,该类可以创建正确的身份验证令牌.

As you can see, it adds a "Bearer" token to the HTTP headers of the request. The SimpleWebToken class is just a custom class I wrote for the occasion, but you can replace it with a better class that creates a correct authentication token.

如果您喜欢其他身份验证方案(例如基本"或摘要"),则可以相应地设置授权标头.

If you prefer a different authentication scheme (such as Basic or Digest), you can set the Authorization header accordingly.