Geeks With Blogs

News Forms Justin Hoffman
Justin Hoffman

Recently I had a need to write some tests making Web Api calls that would be deployable to the build server without any special configuration.What I did was utilize the Self Hosting feature in the Asp.NetWebApi.  First, I created a simple Api controller .


// GET /api/values public class ValuesController : ApiController { public SomeObjects GetByName(string firstName, string lastName) { var someObjects= new List<SomeObject>() { new SomeObject { FirstName = "Tom", LastName = "Jones", Id= 1213 }, new SomeObject { FirstName = "Jane", LastName = "Doe", Id= 1523 }, new SomeObject { FirstName = "John", LastName = "Doe", Id= 3123 } }; return someObjects.Where(x => x.FirstName == firstName && x.LastName == lastName).SingleOrDefault(); } }

Next, I created a simple utility class to execute tests against the hosted service


public static class TestHostingUtil
        public static void ExecuteHostedTest(Action<Task> continuationAction, string routeTemplate = null)
            var routeTempl = "api/{controller}/{id}";
            if (!string.IsNullOrEmpty(routeTemplate))
                routeTempl = routeTemplate;

            var serverConfig = new HttpSelfHostConfiguration("http://localhost:8080/");
            serverConfig.Routes.MapHttpRoute("default", routeTempl, new { id = RouteParameter.Optional, folder = "TestApiControllers" });

            var server = new HttpSelfHostServer(serverConfig);

Note the "folder" param in the HttpRoute registration. In the test project this is the folder under which I added the Api controllers, if they were not in a seperate folder you would leave this blank.

Finally, the usuage for your tests:

        public void Should_Perform_Get()
            TestHostingUtil.ExecuteHostedTest(task =>

                                      // Arrange
                                      var webUtil=
                                          new WebUtil
                                              <SomeObject, SomeObject>(

                                      // Act
                                      var result = webUtil.Get();

                                      // Assert

Posted on Wednesday, May 16, 2012 11:27 AM | Back to top

Comments on this post: Self Host Web Api's for Integration Testing

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Justin Hoffman | Powered by: