【发布时间】:2016-05-27 05:19:18
【问题描述】:
我很难用 Visual Studio 2013 测试我的 API 控制器。我的一个解决方案有一个 Web API 项目和一个测试项目。在我的测试项目中,我有一个单元测试:
[TestMethod]
public void GetProduct()
{
HttpConfiguration config = new HttpConfiguration();
HttpServer _server = new HttpServer(config);
var client = new HttpClient(_server);
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:50892/api/product/hello"),
Method = HttpMethod.Get
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = client.SendAsync(request).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var test = response.Content.ReadAsAsync<CollectionListDTO>().Result;
}
}
我不断收到 404。我尝试使用 Visual Studio (IIS Express) 的一个实例运行我的 API,并尝试在另一个实例中调试此单元测试。但没有运气。我已经验证我可以将此 URL 放在浏览器中(当一个 Visual Studio 正在调试时)并且我看到了我的 JSON 响应。但我不知道如何让它与我的单元测试和HttpClient一起工作。我试图在网上找到示例,但似乎找不到。有人可以帮忙吗?
更新 1: 我尝试添加路线,但没有任何反应。
HttpConfiguration config = new HttpConfiguration();
// Added this line
config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/product/hello/");
HttpServer _server = new HttpServer(config);
var client = new HttpClient(_server);
[...rest of code is the same]
这是我的 API 控制器
[HttpGet]
[Route("api/product/hello/")]
public IHttpActionResult Hello()
{
return Ok();
}
更新分辨率:
如果我在没有HttpServer 对象的情况下新建HttpClient,我就能让它工作。不过,我仍然需要运行两个 VS 实例。 1 运行我的 API 代码,另一个运行单元测试。
这是一个工作方法。
[TestMethod]
public void Works()
{
var client = new HttpClient(); // no HttpServer
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:50892/api/product/hello"),
Method = HttpMethod.Get
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = client.SendAsync(request).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
}
任何人都知道为什么它不能与 HttpServer 和 HttpConfiguration 传递到 HttpClient 一起工作吗?我见过很多使用这个的例子。
【问题讨论】:
-
可能没什么区别,但为什么不直接使用GetAsync呢?
-
您是否在启动时使用 OWIN 管道?您可能需要使用
TestServer。 blogs.msdn.microsoft.com/webdev/2013/11/26/… -
我没有使用owin。
-
你使用的是什么版本的 asp.net-mvc web api?
-
您要测试的方法的代码在哪里?这看起来像是一个集成测试,因为您没有模拟/伪造任何依赖项。
标签: c# unit-testing visual-studio-2013 asp.net-web-api dotnet-httpclient