Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7708245
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T00:33:48+00:00 2026-06-01T00:33:48+00:00

i’ve got an integration test that grabs some json result from a 3rd party

  • 0

i’ve got an integration test that grabs some json result from a 3rd party server. It’s really simple and works great.

I was hoping to stop actually hitting this server and using Moq (or any Mocking library, like ninject, etc) to hijack and force the return result.

is this possible?

Here is some sample code :-

public Foo GoGetSomeJsonForMePleaseKThxBai()
{
    // prep stuff ...

    // Now get json please.
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("Http://some.fancypants.site/api/hiThere");
    httpWebRequest.Method = WebRequestMethods.Http.Get;
    
    string responseText;
    
    using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
    {
        using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
        {
            json = streamReader.ReadToEnd().ToLowerInvariant();
        }
    }
    
    // Check the value of the json... etc..
}

and of course, this method is called from my test.

I was thinking that maybe I need to pass into this method (or a property of the class?) a mocked httpWebResponse or something but wasn’t too sure if this was the way. Also, the response is a output from an httpWebRequest.GetResponse() method .. so maybe I just need to pass in a mocked HttpWebRequest ?.

any suggestions with some sample code would be most aprreciated!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T00:33:50+00:00Added an answer on June 1, 2026 at 12:33 am

    You may wish to change your consuming code to take in an interface for a factory that creates requests and responses that can be mocked which wrap the actual implementation.

    Update: Revisiting

    I’ve been getting downvotes long after my answer was accepted, and I admit my original answer was poor quality and made a big assumption.

    Mocking HttpWebRequest in 4.5+

    The confusion from my original answer lies in the fact that you can mock HttpWebResponse in 4.5, but not earlier versions. Mocking it in 4.5 also utilizes obsolete constructors. So, the recommended course of action is to abstract the request and response. Anyways, below is a complete working test using .NET 4.5 with Moq 4.2.

    [Test]
    public void Create_should_create_request_and_respond_with_stream()
    {
        // arrange
        var expected = "response content";
        var expectedBytes = Encoding.UTF8.GetBytes(expected);
        var responseStream = new MemoryStream();
        responseStream.Write(expectedBytes, 0, expectedBytes.Length);
        responseStream.Seek(0, SeekOrigin.Begin);
    
        var response = new Mock<HttpWebResponse>();
        response.Setup(c => c.GetResponseStream()).Returns(responseStream);
    
        var request = new Mock<HttpWebRequest>();
        request.Setup(c => c.GetResponse()).Returns(response.Object);
    
        var factory = new Mock<IHttpWebRequestFactory>();
        factory.Setup(c => c.Create(It.IsAny<string>()))
            .Returns(request.Object);
    
        // act
        var actualRequest = factory.Object.Create("http://www.google.com");
        actualRequest.Method = WebRequestMethods.Http.Get;
    
        string actual;
    
        using (var httpWebResponse = (HttpWebResponse)actualRequest.GetResponse())
        {
            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                actual = streamReader.ReadToEnd();
            }
        }
    
    
        // assert
        actual.Should().Be(expected);
    }
    
    public interface IHttpWebRequestFactory
    {
        HttpWebRequest Create(string uri);
    }
    

    Better answer: Abstract the Response and Request

    Here’s a safer bare-bones implementation of an abstraction that will work for prior versions (well, down to 3.5 at least):

    [Test]
    public void Create_should_create_request_and_respond_with_stream()
    {
        // arrange
        var expected = "response content";
        var expectedBytes = Encoding.UTF8.GetBytes(expected);
        var responseStream = new MemoryStream();
        responseStream.Write(expectedBytes, 0, expectedBytes.Length);
        responseStream.Seek(0, SeekOrigin.Begin);
    
        var response = new Mock<IHttpWebResponse>();
        response.Setup(c => c.GetResponseStream()).Returns(responseStream);
    
        var request = new Mock<IHttpWebRequest>();
        request.Setup(c => c.GetResponse()).Returns(response.Object);
    
        var factory = new Mock<IHttpWebRequestFactory>();
        factory.Setup(c => c.Create(It.IsAny<string>()))
            .Returns(request.Object);
    
        // act
        var actualRequest = factory.Object.Create("http://www.google.com");
        actualRequest.Method = WebRequestMethods.Http.Get;
    
        string actual;
    
        using (var httpWebResponse = actualRequest.GetResponse())
        {
            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                actual = streamReader.ReadToEnd();
            }
        }
    
    
        // assert
        actual.Should().Be(expected);
    }
    
    public interface IHttpWebRequest
    {
        // expose the members you need
        string Method { get; set; }
    
        IHttpWebResponse GetResponse();
    }
    
    public interface IHttpWebResponse : IDisposable
    {
        // expose the members you need
        Stream GetResponseStream();
    }
    
    public interface IHttpWebRequestFactory
    {
        IHttpWebRequest Create(string uri);
    }
    
    // barebones implementation
    
    private class HttpWebRequestFactory : IHttpWebRequestFactory
    {
        public IHttpWebRequest Create(string uri)
        {
            return new WrapHttpWebRequest((HttpWebRequest)WebRequest.Create(uri));
        }
    }
    
    public class WrapHttpWebRequest : IHttpWebRequest
    {
        private readonly HttpWebRequest _request;
    
        public WrapHttpWebRequest(HttpWebRequest request)
        {
            _request = request;
        }
    
        public string Method
        {
            get { return _request.Method; }
            set { _request.Method = value; }
        }
    
        public IHttpWebResponse GetResponse()
        {
            return new WrapHttpWebResponse((HttpWebResponse)_request.GetResponse());
        }
    }
    
    public class WrapHttpWebResponse : IHttpWebResponse
    {
        private WebResponse _response;
    
        public WrapHttpWebResponse(HttpWebResponse response)
        {
            _response = response;
        }
    
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_response != null)
                {
                    ((IDisposable)_response).Dispose();
                    _response = null;
                }
            }
        }
    
        public Stream GetResponseStream()
        {
            return _response.GetResponseStream();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.