0

I want to Unit Test a method that returns a FileContentResult of a PDF file. I am doing some tests to check the content type & file name, but it would be great if I could also generate the PDF somehow as part of the test? I currently have a method as follows:

    public FileContentResult ConvertToPDF(int baseClassId)
    {
        try
        {
            return new DocumentWriter().ConvertDocumentToPDFSharp(baseClassId);

        }
        catch (Exception ex)
        {
            Logger.Instance.LogError("Error in Assessments_FormHeaderController ConvertToPDF", ex);
            return new FileContentResult(GetBytes("Error fetching pdf, " + ex.Message + Environment.NewLine + ex.StackTrace), "text/plain");
        }
    }

and I am testing with the following:

    [TestMethod]
    public void ReturnFileContentResult()
    {
        DocumentPDFPrinterController pdfController = new DocumentPDFPrinterController();
        FileContentResult result = pdfController.ConvertToPDF(0);

        Assert.IsTrue(result.ContentType == "application/pdf" && result.FileDownloadName.Contains(".pdf"));
    }

Can I add anything to this text which will create the pdf file in a given location(user downloads?).

CJH
  • 1,266
  • 2
  • 27
  • 61

1 Answers1

0

Should have done some more investigating before putting the question out there. I have found simply adding the following got the job done for me:

System.IO.File.WriteAllBytes(@"C:\Users\username\Downloads\Test.pdf", result.FileContents);

That generates my file nicely.

CJH
  • 1,266
  • 2
  • 27
  • 61
  • You can also use the [TestContext.ResultsDirectory](https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.testcontext.resultsdirectory?view=mstest-net-1.2.0) property to get the path to a directory that can be used to store results for a test – BenCamps Dec 14 '18 at 21:46
  • Thanks BenCamps...! Have now looked at this as well. – CJH Dec 19 '18 at 12:01