Tony
Tony

Reputation: 12695

WebAPI - routes (integration) testing - 404 error

I'm trying to make a first integration test of my Web Api project. The target get action is available for anonymous users, but I get the 404 error in the test:

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"));
   }
}

Upvotes: 2

Views: 721

Answers (1)

Nkosi
Nkosi

Reputation: 247153

For in-memory integration test HttpServer uses http://localhost only for the host. no need for the port.

You can also set it as the base address on the client. To test the api controller you would need to configure with your controllers from that project

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
   }
}

Upvotes: 1

Related Questions