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.Buffer = true;
        httpResponse.ContentType = "application/pdf";

        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();
        fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);


        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!");

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s