Mocking an object (HttpWebRequest) with no constructor

2 posts, 0 answers
  1. Devin
    Devin avatar
    9 posts
    Member since:
    Jun 2011

    Posted 09 Aug 2011 Link to this post

    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); }
  2. Ricky
    Ricky avatar
    467 posts

    Posted 10 Aug 2011 Link to this post

    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)
         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,
    the Telerik team

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

  3. DevCraft R3 2016 release webinar banner
Back to Top