3

I'm back filling some unit tests in our app at work, and came across the following method.

public virtual void WriteBodyToRequestStream(HttpWebRequest webRequest, byte[] redirectBodyBuffer) {
    var requestStream = webRequest.GetRequestStream();
    requestStream.Write(redirectBodyBuffer, 0, redirectBodyBuffer.Length);
    requestStream.Close();
}

I'm trying to write a simple test that inserts some text in the stream. The problem I'm having is figuring out how to verify the text after it's written into the stream. Here's what I have so far.

[Test, Ignore("not working yet")]
public void Should_write_to_request_stream()
{
    var request = WebRequest.Create("http://localhost/") as HttpWebRequest;
    request.Method = "POST";
    var encoding = new System.Text.UTF8Encoding();
    var bytes = encoding.GetBytes("testing");
    _helper.WriteBodyToRequestStream(request, bytes);

    var stream = request.GetRequestStream() as MemoryStream;
    var result = System.Text.Encoding.UTF8.GetString(stream.ToArray());

    Assert.AreEqual("testing", result);
}

When I run this test, the stream var is null.

4

1 に答える 1

2

do you really need to pass HttpWebRequest to your WriteBodyToRequestStream method? You really don't care about the HttpWebRequest its more the stream you are interested in:

public virtual void WriteBodyToRequestStream(Stream requestStream , byte[] redirectBodyBuffer) {
//var requestStream = webRequest.GetRequestStream(); remove this line.
requestStream.Write(redirectBodyBuffer, 0, redirectBodyBuffer.Length);
requestStream.Close();
}

This makes your method easily testable (whether its a unit test or integration test I will leave up for discussion ;P)

于 2012-04-26T15:16:18.613 に答える