5

我有以下方法在 HttpResponse 对象中写入流。

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;

    }

为了测试它,我需要恢复处理过的流。有没有办法从 httpResponse 对象中读取流?

4

1 回答 1

2

I have two ideas... one to mock the HttpResponse, and the other is to simulate a web server.

1. 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();
    }        
}

2. Simulate a Web Server

Perhaps you can do this by simulating a web server. It might sound crazy, but it doesn't look like it's that much code. Here are a couple of links about running Web Forms outside of IIS.

Can I run a ASPX and grep the result without making HTTP request?

http://msdn.microsoft.com/en-us/magazine/cc163879.aspx

于 2012-12-18T16:15:31.363 回答