首先,您通常将单元测试项目和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测试服务器和启动类。
感谢您的回答:) – user3825003
如果我能我会给予好评这个10倍! – dcarson
有关测试身份验证,请参阅此帖 - http://stackoverflow.com/a/25057928/968003 –