23 December, 2008

WCF: How to unit test a WCF-service

Unit testing a WCF-service is actually not all that difficult as one might think initially.

The better way of unit testing a WCF-service, is to actually host both the ServiceHost as well as the Client within the unit test at the same time. In this way – you are completely liberated from dependencies and other constraints otherwise imposed.

The Microsoft unit testing framework included in VS (2005/2008/2010) contains a number of attributes that you can use for setting up the servicehost. This is the way of setting up a unit test for testing a WCF-service:

1. Declare a static class member for the ServiceHost:

2. Initialize and open the ServiceHost in the ClassInitialize method of the unittest. This is only run once when the unit test is started.

3. Close the ServiceHost in the ClassCleanup method of unit test.

4. Use the ServiceHost inside all unit test methods as an ordinary WCF-service host. The host will respond as expected and you do not have to start a console behind the unit test to get valid replies from the service.

Of-course you have to setup the app.config for your unit test to make the ServiceHost run as expected (note the ‘local’ endpoint which is referenced in the unit testing). But this is rather conventional WCF-settings.

This is a really nice and clean way of performing unittesting of WCF-services.

A sample (POC) is found here: http://www.clauskonrad.net/download.ashx?id=11

Technorati Tags: ,


black_wizard said...


Eric said...

Thanks, this was clear, concise and helpful to me.

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...