WebAPI - 路由(集成)测试 - 404错误

时间:2017-09-07 15:05:04

标签: c# unit-testing asp.net-web-api2 integration-testing

我正在尝试对我的Web Api项目进行首次集成测试。目标获取操作可供匿名用户使用,但我在测试中收到404错误:

string url = "http://localhost:28000";

var config = new HttpConfiguration();

config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { routetemplate = "Version", id = RouteParameter.Optional });
config.Routes.MapHttpRoute(name: "ApiWithActionName", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });

using (var server = new HttpServer(config))
{
   using (var client = new HttpClient(server))
   {
       var response = client.GetAsync($"{url}/api/values").Result;

       Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK);

       var answer = response.Content.ReadAsStringAsync().Result;

       Assert.IsTrue(answer.Contains("ok"));
   }
}

1 个答案:

答案 0 :(得分:1)

对于内存中集成测试,HttpServer仅对主机使用http://localhost。不需要港口。

您也可以将其设置为客户端上的基本地址。要测试api控制器,您需要使用该项目中的控制器进行配置

var config = new HttpConfiguration();

//Configuration from web project needs to be called so it is aware of api controllers
WebApiConfig.Register(config);

//this would have been done in the Register method called before
//config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { routetemplate = "Version", id = RouteParameter.Optional });
//config.Routes.MapHttpRoute(name: "ApiWithActionName", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });

using (var server = new HttpServer(config)) {
   using (var client = new HttpClient(server)) {
       client.BaseAddress = new Uri("http://localhost/");
       var response = await client.GetAsync("api/values");//resolves to http://localhost/api/values

       //...code removed for brevity
   }
}