Search This Blog

Tuesday, November 15, 2011

How to test WCF services

The typical way of testing WCF services is to create a test project, add a service reference to the project, and then write a test against the client object that is automatically created for you:
  • Create a test project
  • Right-click References and select Add Service Reference
  • In the Address box, type in the URL to the SVC file that is hosted on a web server. You can use the Discover button to find WCF services in the same solution.
  • Select a namespace to use for the service client that will be created, and press OK
This will create a class called <Namespace>.<ServiceName>Client for you, which will act as a client proxy to the WCF service. You can then write unit tests against that class just as you would write unit tests against a regular class. You could have a helper method that would convert some input parameters to the Byte array the WCF service takes, and returns the result. Then, each unit test would just call the helper method with the appropriate input parameters, and do validation on the output. The amount of code needed in each unit test can be minimized, but depends on how much validation needs to be done.

It looks like what you have is a web page that acts as a client to the WCF service. It is possible to have the web page take input parameters as query-string parameters in the URL, and have it write the result to the response, as it is already doing. With this, it would be possible to create web tests to test the WCF service through the web page. However, this requires that the web page be hosted on a web server, and separates related parts of test code.

To answer your questions specifically:
  1. The first approach I mentioned above is probably the best way to test a WCF service. It allows you to test methods/properties exposed in the service contract in the same way as any other client application would use the service.
  2. The amount of code that is necessary really depends on how much validation needs to be done on what is being tested. You can use a web page client as an alternative, in which case the amount of code that is needed may be slightly reduced, but you still need the same inputs to the service and the same validation on the outputs, so if it is not through code, it will be through searching the response from the web page. Using a web page client may even unnecessarily complicate your test code, in things such as parsing the query strings to convert the input parameters to the right types, and then parsing the response text to do validation.
  3. Using WcfTestClient.exe (for more info: http://msdn.microsoft.com/en-us/library/bb552364.aspx)
  4. VSTS 2008 Test Edition is definitely the right tool for testing WCF services. With the service client that is automatically created for you, testing a WCF service becomes a task as simple as testing a regular class. 
Post a Comment

Popular Posts