Search code examples
web-servicesunit-testingc#-4.0deserializationrhino-mocks

Unit test for web service (Service Reference) - xml deserialization


In Summary

I need a way to deserialize an XML string into an object normally returned by a 3rd party webservice.

Using C#.

In Detail

I have code that consumes a 3rd party Service Reference (Web Service) - so the usual stuff: we pass in a Request object and it returns a Response object.

Regarding unit testing - I'm not interested in the inner workings of the Service Reference since this is a 3rd party service. I'm only interested in two things:

  1. Does my code generate the correct Request object?
  2. When the Service Reference returns it's response, do I process this response correctly?

Taking each in turn:

Does my code generate the correct Request object?

This I can do. If anyone's interested in this, what I do is to replace my service reference with a RhinoMocks Mock object. In my unit test I call the method on my Mock and then check the arguments passed in, comparing the actual Request object against the expected Request object.

When the Service Reference returns it's response, do I process this response correctly?

What I want to do here is to create a RhinoMocks Stub of my service reference, so that when it's called this stub returns a response object populated with my test data.

The problem that I face is that the response objects returned by this particular 3rd party service are extremely complex. If I were to attempt to create one by hard-coding all the property values by hand then this would probably take me the best part of a whole day.

However, what I can very easily do is to capture the XML serialized response from this service. I could then easily edit it's values and store this XML in one of my unit tests.

What I'm after is an easy way to then "deserialize" this "test" XML into a response object and use this to program the response from my Stub.

Any help would be much appreciated.

Thanks

Griff


Solution

  • Turns out that this is quite simple:

    public static object Deserialize(string xml, Type toType)
    {
        using(Stream stream = new MemoryStream())
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            var s = new XmlSerializer(toType, "http://^your url^");
            return s.Deserialize(stream);
        }
    }
    

    Note that if you're using XML from a SOAP request, strip the SOAP envelop off first.

    Griff