Mocking WebResponse's from a WebRequest

Posted by Rob Cooper on Stack Overflow See other posts from Stack Overflow or by Rob Cooper
Published on 2008-09-17T20:21:04Z Indexed on 2010/04/03 16:53 UTC
Read the original article Hit count: 526

I have finally started messing around with creating some apps that work with RESTful web interfaces, however, I am concerned that I am hammering their servers every time I hit F5 to run a series of tests..

Basically, I need to get a series of web responses so I can test I am parsing the varying responses correctly, rather than hit their servers every time, I thought I could do this once, save the XML and then work locally.

However, I don't see how I can "mock" a WebResponse, since (AFAIK) they can only be instantiated by WebRequest.GetResponse

How do you guys go about mocking this sort of thing? Do you? I just really don't like the fact I am hammering their servers :S I dont want to change the code too much, but I expect there is a elegant way of doing this..

Update Following Accept

Will's answer was the slap in the face I needed, I knew I was missing a fundamental point!

  • Create an Interface that will return a proxy object which represents the XML.
  • Implement the interface twice, on that uses WebRequest, the other that returns static "responses".
  • The interface implmentation then either instantiates the return type based on the response, or the static XML.
  • You can then pass the required class when testing or at production to the service layer.

Once I have the code knocked up, I'll paste some samples.

Thanks Will :)

© Stack Overflow or respective owner

Related posts about Xml

Related posts about web-services