7

我有一个httppost web api方法。我需要传入令牌作为授权头并收集响应。如何使用令牌单元测试帖子(web-api)呼叫?

我使用web-api 2.我的post方法返回IHttpActionResult ok(模型)。

我使用POSTMAN休息客户端测试了web-api,它工作正常。

我被困在一个点,在哪里我不能写一个UNIT-TEST来测试我的API。

此外,我不能在同一个解决方案中有单元测试项目和web-api项目吗?我尝试将单元测试项目和web-api项目设置为启动项目。但单元测试项目只是一个库,所以不起作用。

有人可以引导我通过这个?

回答

13

首先,您通常将单元测试项目和Api项目放在同一个解决方案中。但是API项目应该是启动项目。然后,您可以使用Visual Studio测试资源管理器或其他等效(f.x。构建服务器)来运行您的单元测试。

为了测试您的API控制器,我建议您在单元测试中创建一个Owin测试服务器,并使用它来对您的API执行HTTP请求。

[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. 

     } 
    } 

然而,你将不得不使用依赖注入来注入你的模拟/存根。您必须在Tests项目的启动类中配置依赖注入。

Here's这篇文章更详细地解释了Owin测试服务器和启动类。

+0

感谢您的回答:) – user3825003

+0

如果我能我会给予好评这个10倍! – dcarson

+0

有关测试身份验证,请参阅此帖 - http://stackoverflow.com/a/25057928/968003 –

0

为了便于单元,路线和集成测试,您可以检查MyTested.WebApi,它可以让你做到以下几点:

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