This is a migrated thread and some comments may be shown as answers.

Mocking an object (HttpWebRequest) with no constructor

1 Answer 32 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Devin
Top achievements
Rank 1
Devin asked on 09 Aug 2011, 09:20 PM
I'm trying to Mock an HttpWebRequest (from the System.Net namespace) object, but I keep getting runtime errors.  It seems that the only constructor for HttpWebRequest is protected and has been Deprecated by Microsoft.  If this is the case, how would I could about Mocking an object which doesn't give access to it's constructor?

Here is my code.  It dies when Arranging the HttpUtils.CreateWebRequest call.  CreateWebRequest is  a static method of the non-static class HttpUtils.

private HttpWebRequest _webRequestMock;

private void SetupMocks()
{
	_webRequestMock = Mock.Create<HttpWebRequest>();
_webResponseMock = Mock.Create<WebResponse>(); Mock.SetupStatic<HttpUtils>(Behavior.Strict); Mock.Arrange(() => HttpUtils.CreateWebRequest(Arg.IsAny<string>())).Returns(_webRequestMock); Mock.Arrange(() => _webRequestMock.GetResponse()).Returns(_webResponseMock); }

1 Answer, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 10 Aug 2011, 10:13 AM
Hi Devin,
Thanks again for sending the issue.Here when i write the following:
var webRequestMock = Mock.Create<HttpWebRequest>();

It does fire up the protected constructor but fails with the following exception:
Object reference not set to an instance of an object.

The reason here is that if you open up the constructor using a decompiler you will see something like:

protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext)
     : base(serializationInfo, streamingContext)
   {
     ExceptionHelper.WebPermissionUnrestricted.Demand();
     if (Logging.On)
       Logging.Enter(Logging.Web, (object) this, "HttpWebRequest", (object) serializationInfo);
     this._HttpRequestHeaders = (WebHeaderCollection) serializationInfo.GetValue("_HttpRequestHeaders", t


The solution here is to use the Constructor.Mocked switch that will skip the base ctor call.
HttpWebRequest webRequest = Mock.Create<HttpWebRequest>(Constructor.Mocked);


Once you have done it the rest should work as expected.

Kind Regards,
Mehfuz
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get now >>

Tags
General Discussions
Asked by
Devin
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Share this question
or