Mocking HttpWebResponse

1,134 views
Skip to first unread message

to...@spidertracks.co.nz

unread,
Mar 10, 2010, 8:50:36 PM3/10/10
to Moq Discussions
Hey guys,
I need to simulate failures and catching those errors with an
HttpWebResponse. I've tried mocking it up, but I can't seem to do
so. I always receive this error.

System.ArgumentException: Invalid setup on a non-overridable member:
w => w.StatusCode

I know this is due to StatusCode not being a virtual method. Now the
million dollar question, how can I correctly moq a response? I can't
find anything on the web, and it's getting difficult to wire
everything up to test properly without this mocking.

Below is my code


Mock<HttpWebResponse> webResponse = new Mock<HttpWebResponse>();

//return our wrapped memory stream on the mock object
webResponse.Setup(w => w.GetResponseStream()).Returns(new
MemoryStream(Encoding.Unicode.GetBytes(GetMockXML(ErrorResponse))));

//return 400 of our error code so that the message is properly parsed
webResponse.Setup(w =>
w.StatusCode).Returns(HttpStatusCode.BadRequest);

WebException webException = new WebException("Excception", new
Exception("Failed to connect"), WebExceptionStatus.UnknownError,
webResponse.Object);


Mock<IXeroRequest> mock = new Mock<IXeroRequest>();

//throw our web exception from above. We should get an admin message
that an error 400 has occured
mock.Setup(m => m.MakeRequest(It.IsAny<XElement>(),
It.IsAny<XeroApi>(), XeroRequestType.Put,
It.IsAny<XeroAuth>())).Callback((XElement e, XeroApi xApi,
XeroRequestType xrt, XeroAuth a) =>
SetXElement(e)).Throws(webException);

ServiceLocator.Register(typeof(IXeroRequest), mock.Object);

Chris Missal

unread,
Mar 10, 2010, 11:31:28 PM3/10/10
to moq...@googlegroups.com
This isn't the answer to what you're asking exactly, but this method allows us to test some request/response stuff in an application. Maybe you can use something related:

    public class Client
    {
        protected readonly IClientConfiguration clientConfiguration;
        protected readonly WebClient webClient;

        public Client(IClientConfiguration clientConfiguration)
        {
            this.clientConfiguration = clientConfiguration;
            webClient = GetWebClient();
        }

        protected virtual WebClient GetWebClient()
        {
            return new WebClient();
        }

        public string SendConfirmation(string data)
        {
            return webClient.UploadString(clientConfiguration.ConfirmationUrl, data);
        }
    }

The Client class is just a thin wrapper around System.Net.WebClient. It's the virtual member call in the constructor that allows us to sub-class and provide a mock for the WebClient.

That's about the extent of my help, I hope it might be useful, cheers.






--
Chris Missal
http://chrismissal.lostechies.com/

Daniel Cazzulino

unread,
Mar 11, 2010, 10:04:37 AM3/11/10
to moq...@googlegroups.com
Unfortunately, I don't think HttpWebResponse was designed with mocking in mind.

You should treat that as a legacy API that you have to isolate behind a thin interface.

This post should give some ideas on how to do it (talks about mocking WCF which is similar): http://weblogs.asp.net/cibrax/archive/2008/05/16/unit-tests-for-wcf.aspx

/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


Reply all
Reply to author
Forward
0 new messages