Unit Testing Functions that Access Web-Services

Sorry about the title but I couldn't come up with anything shorter to describe the topic.

Background

The system we built for our client makes use of an external 3rd party web-service for certain data. Naturally there are a number of things that can happen which we need to handle gracefully.

  1. Web service not reachable
  2. XML returned not well formed
  3. Data doesn't conform to business rules (e.g. old data, incorrect datatypes etc)

Unit Testing

So how do we make sure that our code handles the above cases gracefully and correctly? We don't have the ability to influence the web service nor are we able to ask the provider to force the above cases just so we can test our code.

Ideally we would create a "surrogate" web service where we can influence the results returned, but that would mean altering our function to point somewhere else just for the tests. I don't want to add code to the function just for testing purposes and then have to leave it in there or risk taking it out and breaking something in the process.

Hosts file

This is probably not a new idea but I thought why not just alter the Hosts file on the server? That way when the function calls the web service I can route it back to the server. I then just need to set up the appropriate virtual directory to mimic the structure of the web service URL and then finally build my simple surrogate web service.

Results

It sounds like a lot of work just to test the function but it really didn't take all that long to do and we can be sure that this really important function is able to handle every exception we can think up.

We can test how our function handles unexpected results without altering it and that, to me, is well worth the effort.

Comments
Peter Bell's Gravatar This is a pretty common issue with unit testing. You want to be able to test exception conditions, and you also want the test to run faster than an external element (web service, database, etc) will provide. The answer is usually to mock out the class file that actually does the access so you can test the rest of the system.
# Posted By Peter Bell | 5/8/08 5:50 AM