Mocking the response stream in HttpWebResponse using Moq

I'm using Moq to mock HttpWebResponse for unit testing. I created a mock class that inherits from the class I'm trying to test and I'm overriding the method that returns the HttpWebResponse. I want to write a JSON string to the response stream from the unit test but I get an ArgumentException when trying to read the stream saying "Stream was not readable".

Here is what I have:

public class ParentClass
{
    private string ProcessResponse(HttpWebResponse response)
    {
        string json = String.Empty;
        using (var streamReader = new StreamReader(response.GetResponseStream())) //exception here
        {
            json = streamReader.ReadToEnd();
        }
        return json;
    }

    //other stuff
}

public class MockClass : ParentClass
{
    public Stream responseStream = new MemoryStream();

    public void WriteJson(string json)
    {
        using(var writer = new StreamWriter(responseStream))
        {
            writer.Write(json);
        }
    }

    protected override HttpWebResponse GetResponse(HttpWebRequest request)
    {
        var response = new Mock<HttpWebResponse>();
        response.Setup(r => r.GetResponseStream()).Returns(responseStream);
        return response.Object;
    }
}

Answers


The problem seemed to be with the using statement. Here are the changes I made:

public void WriteJson(string json)
{
    var jsonBytes = Encoding.UTF8.GetBytes(json);
    responseStream.Write(jsonBytes, 0, jsonBytes.Length);
    responseStream.Seek(0, SeekOrigin.Begin);
}

It's safer to use an overload of StreamWriter which leaves the underlying stream open:

public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)

Need Your Help

Where are dll libraries stored in VS .Net?

c# dll shared-libraries

I wonder where dll files are stored in Visual Studio and whether its the best way to keep them there or consolidate elsewhere for the following cases:

How to get back the control on embedded text on a UIImage in Swift

ios swift text uiimage

I work on a swift application that allows to take a picture and embeds some text on it (for example: the current date). I have some labels (containing the current date, for example) appearing on the