How do I unit test call post (web-api) with a token?

I have a httppost web api method. I need to pass the token as the authorization header and collect the response.

I am using web-api 2. My post method returns IHttpActionResult ok (model).

I tested web-api using the POSTMAN rest client, which works.

I am stuck at a point where I cannot write UNIT-TEST to test my API.

Also, can I create a Unit test project and a web-api project in the same solution? I tried to configure the Unit test project and the web-api project as startup projects. But the Unit test project is just a library, so it won’t work.

Can someone please guide me through this?

+7
web-applications unit-testing asp.net-web-api asp.net-web-api2
source share
2 answers

For starters, you usually use the Unit test project and the Api project in the same solution. However, the API project must be a launch project. You can then use the visual studio test explorer or another equivalent (fx Build Server) to run your unit tests.

To test your API controllers, I suggest you create an Owin test server in your unit tests and use it to make HTTP requests against your API.

[TestMethod] public async Task ApiTest() { using (var server = TestServer.Create<Startup>()) { var response = await server .CreateRequest("/api/action-to-test") .AddHeader("Content-type", "application/json") .AddHeader("Authorization", "Bearer <insert token here>") .GetAsync(); // Do what you want to with the response from the api. // You can assert status code for example. } } 

However, you will need to use dependency injection to inject your mocks / stubs. You will need to configure your dependency injection in the start class in the Tests project.

The following is an article explaining in more detail the Owin test server and the launch class.

+13
source share

To simplify unit tests, route and integration, you can check MyTested.WebApi , which allows you to do the following:

 MyWebApi .Server() .Starts<Startup>() .WithHttpRequestMessage(req => req .WithRequestUri("/api/Books/Get") .WithMethod(HttpMethod.Get) .WithHeader(HttpHeader.Authorization, "Bearer " + this.accessToken)) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.OK) .WithResponseModelOfType<List<BookResponseModel>>() .Passing(m => m.Count == 10); 
0
source share

All Articles