How to write integration test for asp.net web api

走远了吗. 提交于 2019-12-22 08:37:16

问题


I am busy design a web service with asp.net web api. And I want to start doing unit tests on each controller.

here is my test class so far:

[TestClass]
public class MyDevicesControllerTest
{
    [TestMethod]        
    public void TestValidUser()
    {
        MyDeviceController controller = new MyDeviceController();
        var result = controller.Get();

    }

    [TestMethod]
    public void TestInvalidUser()
    {
        MyDeviceController controller = new MyDeviceController();            
        var result = controller.Get();
    }
}

But my web service makes use of token authentication. So I some how need to emulate the authentication process.

So I was thinking my i not maybe make user of a Http Request to test it? Ie instead of testing the controller I just make a http Request and check its answer?

What is the easier / better way to go about testing it?


回答1:


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:

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

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.



来源:https://stackoverflow.com/questions/22293503/how-to-write-integration-test-for-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!