Search code examples
c#testingapproval-tests

Approvaltests and PDF


Can I use ApprovalTests with PDF's? I tried using the FileLauncher but it seems the identical PDF's are slightly different at file (bit) level. Or did I use it wrongly?

[TestMethod]
[UseReporter(typeof(FileLauncherReporter))]
public void TestPdf()
{
    var createSomePdf = PdfCreate();

    ApprovalTests.Approvals.Verify(new FileInfo(createSomePdf.FileName));

}

Solution

  • The Pdf is most likely being created with a timestamp. Depending on the method used to create the pdf, you might be able to mock out the created time. but I had to scrub it.

    Here's the code I used to do that.

        public static void VerifyPdf(string coverFile)
        {
            ScrubPdf(coverFile);
            Approvals.Verify(new ExistingFileWriter(coverFile));
        }
    
        private static void ScrubPdf(string coverFile)
        {
            long location;
            using (var pdf = File.OpenRead(coverFile))
            {
                location = Find("/CreationDate (", pdf);
    
            }
            using (var pdf = File.OpenWrite(coverFile))
            {
                pdf.Seek(location, SeekOrigin.Begin);
    
                var original = "/CreationDate (D:20110426104115-07'00')";
                var desired = new System.Text.ASCIIEncoding().GetBytes(original);
    
                pdf.Write(desired, 0, desired.Length);
                pdf.Flush();
            }
        }