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:
 image

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

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

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.
image

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.
image

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

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

Technorati Tags: ,

4 comments:

black_wizard said...

Thanks!

Eric said...

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

college homework said...

This is the final test that I have been through on every stage which is going on from the very first time. It is the surety that you have been going through the rightful programming.

sriram said...

Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.

software testing course in chennai

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...