我有一个 httppost web api 方法。我需要传入一个 token 作为授权 header 并收集响应。
我正在使用 web-api 2。我的 post 方法返回 IHttpActionResult ok(model)。
我已经使用 POSTMAN rest 客户端测试了 web-api,它可以工作。
我被困在一个点上,我无法编写 UNIT-TEST 来测试我的 API。
另外,我不能在同一个解决方案中拥有单元测试项目和 web-api 项目吗?我尝试将单元测试项目和 web-api 项目设置为启动项目。但是单元测试项目只是一个库,所以它不起作用。
有人可以指导我完成这个吗?
最佳答案
首先,您通常将单元测试项目和 Api 项目放在同一个解决方案中。但是 API 项目应该是启动项目。然后,您可以使用 Visual Studio 测试资源管理器或其他等效工具(f.x. 构建服务器)来运行您的单元测试。
要测试您的 API Controller ,我建议您在单元测试中创建一个 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.
}
}
但是,您将不得不使用依赖注入(inject)来注入(inject)您的模拟/ stub 。您必须在测试项目的启动类中配置依赖注入(inject)。
Here's一篇更详细地解释 Owin 测试服务器和启动类的文章。
关于unit-testing - 如何使用 token 对帖子(web-api)调用进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24674088/