Search code examples
c#asp.netpdfapproval-tests

Specifying the test output path using ApprovalTests.Net to support multiple files


I am writing an application which generates PDF files from HTML markup (using a third party library to do so).

I'd like to be able to approval test the output of these PDF files so to do so I've been looking at the ApprovalTests.Net library.

My issue is while ApprovalTests.Net has native support for PDF equality checking, the PDF generation tool will generate subtly different internal markup each time the PDF file is generated. (Font file names are compressed and randomized, file id's change etc).

It seems the best way to achieve a good approval test will be to flatten the PDF document into a series of images and use the binary comparison/load an image diff tool to approval test the documents.

This is all fairly trivial.

My problem arises when dealing with multi-page pdf documents. Each page will produce a new image and thus my test needs to loop over each page and check against the approved file.

I cant seem to find any documentation to specify the approved file name.

Can anyone with experience working with the Approval Tests framework provide any insight?

Alternatively any other frameworks which will allow me to approval test a collection of images?

Thanks.


Solution

  • Create a new derived class of ApprovalBinaryWriter and override the GetApprovalFilename and GetReceivedFilename and inject the index into the constructor.

    public class CustomBinaryWriter : ApprovalBinaryWriter
    {
        private readonly int _index;
    
        public CustomBinaryWriter(byte[] data, string extensionWithoutDot, int index)
            : base(data, extensionWithoutDot)
        {
            _index = index;
        }
    
        public override string GetApprovalFilename(string basename)
        {
            return string.Format("{0}_{1}{2}{3}", basename, _index, WriterUtils.Approved, ExtensionWithDot);
        }
    
        public override string GetReceivedFilename(string basename)
        {
            return string.Format("{0}_{1}{2}{3}", basename, _index, WriterUtils.Received, ExtensionWithDot);
        }
    }
    

    Then you can call this with

    Approvals.Verify(new CustomBinaryWriter(doc, "png", 1));