我正在使用web-api 2.我的post方法返回IHttpActionResult ok(模型).
我使用POSTMAN rest客户端测试了web-api,它可以工作.
我陷入困境,我无法编写UNIT-TEST来测试我的API.
另外,我不能将Unit测试项目和web-api项目放在同一个解决方案中吗?我尝试将单元测试项目和web-api项目设置为启动项目.但单元测试项目只是一个库,因此无法工作.
有人可以指导我完成这个吗?
要测试您的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测试服务器和启动类.