c# how to get a stream processed by httpResponse.BinaryWrite

I have the following method that writes a stream in a HttpResponse object.

public HttpResponse ShowPDF(Stream stream)
    {
        MemoryStream memoryStream = (MemoryStream) stream;

        httpResponse.Clear();
        httpResponse.Buffer = true;
        httpResponse.ContentType = "application/pdf";
        httpResponse.BinaryWrite(memoryStream.ToArray());
        httpResponse.End();

        return httpResponse;

    }

In order to test it, I need to recover the processed stream. Is there someway to read the stream from the httpResponse object?

Mocking HttpResponse

I wrote this before I knew which mocking framework you used. Here’s how you could test your method using TypeMock.

This assumes that you pass your httpResponse variable to the method, changing the method as follows:

public void ShowPDF(Stream stream, HttpResponse httpResponse)

Of course you would change this to passing it to a property on your Page object instead, if it is a member of your Page class.

And here’s an example of how you could test using a fake HttpResponse:

internal void TestPDF()
{
    FileStream fileStream = new FileStream("C:\\deleteme\\The Mischievous Nerd's Guide to World Domination.pdf", FileMode.Open);
    MemoryStream memoryStream = new MemoryStream();
    try
    {
        memoryStream.SetLength(fileStream.Length);
        fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);

        memoryStream.Flush();
        fileStream.Close();

        byte[] buffer = null;

        var fakeHttpResponse = Isolate.Fake.Instance<HttpResponse>(Members.ReturnRecursiveFakes);
        Isolate.WhenCalled(() => fakeHttpResponse.BinaryWrite(null)).DoInstead((context) => { buffer = (byte[])context.Parameters[0]; });

        ShowPDF(memoryStream, fakeHttpResponse);

        if (buffer == null)
            throw new Exception("It didn't write!");
    }
    finally
    {
        memoryStream.Close();
    }        
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s