Unit test Web Api methods with in-memory HttpServer

Here are the steps to test your Web Api methods with an in-memory webserver. We have a simple Web Api project with 1 method:
/api/test returns "hello".

This unit test method can be used in Web API v1. In Web Api v2 there are some other methods (with Owin).

  • Add new class project
  • Add a reference to the Web Api project to be tested
  • Iin the Nuget package window: install-package nunit (or install your favorite unit tester)
  • install-package Microsoft.AspNet.WebApi -version 4.0.30506.0
  • Add reference to System.Web.dll
  • Add a new Class with Unit test code:

    [TestFixture]
    public class UnitTest
    {
        [Test]
        public void Test()
        {
            //arrange
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { routetemplate = "Version", id = RouteParameter.Optional });

            var server = new HttpServer(config);
            var client = new HttpClient(server);

            // act
            var response = client.GetAsync("http://server/api/test").Result;

            //assert
            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            var answer= response.Content.ReadAsStringAsync().Result;
            Assert.IsTrue(answer.Contains("hello"));
        }
    }

In this test a HttpServer is started with the same configuration as the Web Api project, and a HttpClient is created. After that, a request is fired and the response
is analysed.
And the test should work šŸ™‚ However I had some issues to get this working, in the response there was always a HTPP 404 not found result. This is solved by calling in the test first some method of the Web Api project (for example the configuration object).

Advertisements

5 thoughts on “Unit test Web Api methods with in-memory HttpServer

  1. Good morning great article. Can you explain what you did when you say “This is solved by calling in the test first some method of the Web Api project (for example the configuration object).”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s