Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a WebApi service?

I'm really new to WebApi and I've been reading information about it but I don't know how to start my application.

I already had a project with many WFC services with .Net 3.5. So, I updated my project to 4.5.1. Then I created a controller with the Visual Studio 2012 Wizard. Then, when the controller is created, I see a class as a template with the get, post, put, delete methods. So I place my post method and finally I want to test the service with a HttpClient.

I tried to apply the solution in green from the following forum: How to post a xml value to web api?

I'm gonna receive a XML string with the structure of a Contract model.

I run my project into Visual Studio Development Server.

But I have troubles with URL to test my service.

I saw many pages where people do something like this http://localhost:port/api/contract. But I don't still know how it works. So how can I do to test my service? What is it my path or url to test my service?

like image 413
Maximus Decimus Avatar asked Jun 04 '15 14:06

Maximus Decimus


1 Answers

WebApi, like MVC, is all based on the routing. The default route is /api/{controller}/{id} (which could, of course, be altered). This is generally found in the ~/App_Start/WebApiConfig.cs file of a new project, but given you're migrating you don't have it most likely. So, to wire it up you can modify your Application_Start to include:

GlobalConfiguration.Configure(WebApiConfig.Register);

Then, define that class:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

If you created a TestController controller and wanted to make a POST request to the instance running locally, you'd access http://localhost:12345/api/Test/ (with the appropriate verb). 12345 would be the local port that Visual Studio is using to host your service (and can be found by viewing the project's properties, then navigating to the "Web" tab).

Having said that, testing is probably best performed on the the project (without making an external call). There are several posts on the subject, but generally come down to something like the following:

[TestMethod]
public void Should_Return_Single_Product()
{
    // Arrange
    var repo = new FakeRepository<Widget>();
    var controller = new WidgetController(repo);
    var expected = repo.Find(1);

   // Act
   var actual = controller.GetWidget(1) as OkNegotiatedContentResult<Widget>;

   // Assert
   Assert.IsNotNull(actual);
   Assert.AreEqual(expected.Id, actual.Content.Id);
}
like image 96
Brad Christie Avatar answered Oct 11 '22 20:10

Brad Christie