单元测试FileStreamResult

时间:2012-08-10 09:09:31

标签: asp.net-mvc-3 unit-testing sharpziplib filestreamresult

我有一个Controller通过FileStreamResult返回SharpZipLib(我已经尝试了DotNetZip并且没有区别。)

using (var buffer = new MemoryStream())
{
    using (var zipStream = new ZipOutputStream(buffer))
    {
        zipStream.PutNextEntry(new ZipEntry("The Simpsons"));
        var bart = Encoding.UTF8.GetBytes("Homer <3 donuts");
        zipStream.Write(bart, 0, bart.Length);
        zipStream.IsStreamOwner = false;    
        return File(buffer, MediaTypeNames.Application.Zip, fileName);
    }
}

我正在尝试对此进行单元测试:

var controller = new SimpsonsController();
var result = controller.ConfigurationReport(id);
Assert.IsInstanceOf<FileStreamResult>(result);

var streamResult = (FileStreamResult) result;
var zipInputStream = new ZipInputStream(streamResult.FileStream);

Assert.IsNotNull(zipInputStream);

var zipEntry = zipInputStream.GetNextEntry();
Assert.AreEqual("The Simpsons", zipEntry.Name);

现在单元测试失败了:

System.ObjectDisposedException : Cannot access a closed Stream.
   at System.IO.__Error.StreamIsClosed()
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.Fill()
   at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeByte()
   at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeInt()
   at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry()

如果我尝试通过浏览器直接下载,则具有类似堆栈跟踪的IIS 500:

Cannot access a closed Stream.
System.ObjectDisposedException: Cannot access a closed Stream.
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase response)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)

有没有人测试过这种基于流的文件返回控制器?你是怎么成功的?我应该不处理我的课程吗?真的?

1 个答案:

答案 0 :(得分:1)

试试这个,我认为你的问题是你正在处理正在返回的流。

public FileStreamResult PDF()
{
    MemoryStream buffer = new MemoryStream();
    using (var zipStream = new ZipOutputStream(buffer))
    {
        zipStream.PutNextEntry(new ZipEntry("The Simpsons"));
        var bart = Encoding.UTF8.GetBytes("Homer <3 donuts");
        zipStream.Write(bart, 0, bart.Length);
        zipStream.IsStreamOwner = false;
    }
    return File(buffer, MediaTypeNames.Application.Zip, fileName);
}

请查看此https://stackoverflow.com/a/10891136/985284并关注Cheeso的其他帖子以获取更多信息。