asp.net-mvcunit-testingfilestreamresult

ASP.NET MVC Moq unit testing against a controller that returns FileStreamResult


I am writing a test case against a controller that returns a pdf file.

Code for controller :

  public FileStreamResult GeneratePdfReport(string context)
    {
        byte[] pdfReportContents = _helpPageBusinessService.GetHelpPagesAsPdf();
        Stream stream = new MemoryStream(pdfReportContents);
        HttpContext.Response.AddHeader("content-disposition", "attachment; filename=GSFA_Help_Pages_Printout.pdf");
        return new FileStreamResult(stream, "application/pdf");
    }

Unit test code :

 [TestMethod]
    public void GeneratePdf()
    {
        var controller = new HelpController(_helpPageBusinessServiceReportServices, Logger);
        try
        {
            var result = controller.GeneratePdfReport("Work_Request_Section");
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.FileStream);
        }
        finally
        {
            controller.Dispose();
        }
    }

This unit test case does not work, it always fail as HttpContext is null.

Does anybody out there know how to write unit test case against this type of controller ?

Much appreciated !

Jeffery


Solution

  • You need to mock the HttpContext and the response objects. Also your controller action could be shortened a bit:

    public ActionResult GeneratePdfReport(string context)
    {
        byte[] pdfReportContents = _helpPageBusinessService.GetHelpPagesAsPdf();
        HttpContext.Response.AddHeader("content-disposition", "attachment; filename=GSFA_Help_Pages_Printout.pdf");
        return File(pdfReportContents, "application/pdf");
    }