I have a httppost web api method. I need to pass in a token as an authorization header and collect the response.
I am using web-api 2. My post method returns IHttpActionResult ok(model).
I have tested the web-api using POSTMAN rest client, which works.
I am stuck at a point, where in I am not able to write a UNIT-TEST to test my API.
Also, can't I have the Unit test project and the web-api project in the same solution? I tried setting unit test project and web-api project as startup projects. But Unit test project is just a library so that would not work.
Can someone please guide me through this ?
Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.
To start with, you usually have the Unit test project and the Api project in the same solution. However the API project should be the startup project. You then use the visual studio test explorer or another equivalent(f.x. a build server) to run your unit tests.
To test your API controllers i would suggest you create a Owin test server in your unit tests and use it to execute 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.
}
}
You will however have to use dependency injection to inject your mocks/stubs. You would have to configure your dependency injection in a startup class in your Tests project.
Here's an article which explains the Owin test server and the startup class in more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With