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
  • what you have there is not a Unit Test; it's an Integration Test Commented Apr 25, 2012 at 20:15
  • What is the _helper object and what does it do, can you show source code? Commented Apr 25, 2012 at 20:22
  • @Bronumski The rest of the class is unrelated to the method in question, so it's irrelevant in this context. Commented Apr 25, 2012 at 20:52
  • 1
    Not if your question is about why the request stream is null and you are calling the method WriteBodyToRequestStream on the helper object with the request you are trying to test. Commented Apr 26, 2012 at 8:19

1 Answer 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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.