0

我想对返回 PDF 文件的 FileContentResult 的方法进行单元测试。我正在做一些测试来检查内容类型和文件名,但如果我也能以某种方式生成 PDF 作为测试的一部分,那会很棒吗?我目前有一个方法如下:

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

我正在测试以下内容:

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

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

我可以在此文本中添加任何内容,以在给定位置创建 pdf 文件(用户下载?)。

4

1 回答 1

0

在提出问题之前应该做更多的调查。我发现只需添加以下内容即可为我完成工作:

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

这很好地生成了我的文件。

于 2018-12-14T13:32:30.153 回答