Monday 10 December 2012

Testing an WCF Rest Service directly and via a local instance created by WebServiceHost

Here is an example of a simple REST based WebService which is tested using 3 techniques:

  • IIS
  • Direct object creation
  • Locally hosted instance of the WCF service (using .Net's WebServiceHost class)


It all starts with an Interface definition:

image

Which is implemented by

image

Testing Version method using IIS/Cassini

To access this Service in IIS/Cassini, we call the SetRouteTable method from the Global.asax.cs Application_Start callback:

image

Which sets the AdminRest as the route (i.e. url path) into the Admin_REST service

image

Since we have the help pages enabled (on web.config)

image

We can view a wsdl-type-helper page at http://localhost:3187/AdminREST/help

image
image

And invoke the Version method using http://localhost:3187/AdminREST/Version

image


Testing Version method directly

Inside a VisualStudio 2010 Test Project: image lets add a test that creates an instance of the AdminRest class and invokes it directly (note that this technique will not work for tests that require live (or configured) Asp.NET Http objects)

image

When executed image the UnitTest should succeed and show the version number in its Output window:

image 


Testing Version method using a WCF Host

A more interesting/powerful technique to host the WCF service temporarily on a local port, and access the service via HTTP.

image 

The code above is used by this Unit Test that opens and closes the WCF port during its execution:

image

Here is the output of the the CheckWebServicesHost test:

image

To make this work (and to help debugging) I added/used the DNS entry local (instead of localhost) , which allowed me to view the WCF traffic in Fiddler:

image

Note that the local DNS mapping needs to defined in the system32/etc/hosts file:

image

Another change that I had to do, was to give my current user account, the ability to bind to the 20000 port.

This was done using the HttpNamespaceManager.zip tool available from the AddressAccessDeniedException: HTTP could not register URL http://+:8080/<…> MSDN Article.


image image

Here are couple posts that explain why this last step was required: