简体   繁体   中英

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;
    }
}

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);
}

使用StreamWriter的重载使基础流保持打开状态是更安全的:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM