2017-09-07 21 views
0

Web APIプロジェクトの最初の統合テストを実行しようとしています。ターゲットgetアクションは、匿名ユーザーのために利用可能ですが、私はテストで404エラーが表示されます。WebAPI - ルート(統合)テスト - 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")); 
    } 
} 
+0

'HttpServer'をテストするときは' localhost'だけを使用します。ポートの必要はありません。 – Nkosi

答えて

0

メモリ内の統合テスト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 
    } 
}