How to write integration holidays for asp.net web api

I am designing a web service using asp.net web api. And I want to start performing unit tests on each controller.

here is my test class:

[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 uses token authentication. Therefore, I need to somehow emulate the authentication process.

So, I thought that I can’t make an HTTP request to check it? Those. instead of testing the controller, I just make an http request and check its response?

How is it easier or better to test it?

+4
source share
1 answer

-API ASP.NET , . , - " TDD" , :

HTTP. :

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

, "" HTTP- . SimpleWebToken - , , , .

(, Basic Digest), .

+5

Source: https://habr.com/ru/post/1530920/


All Articles