6.11.  Validate PDF from Database

Initial Situation

An application stores PDF documents into a database.

Problem

How does one ensure that the PDF document in the database contains the expected data? And how should the test to be written so that it can be repeated?

Solution Approach

After the application has written the PDF into the database, PDFUnit reads the PDF from the database as an InputStream and executes your tests. DBUnit was used to reset the database each time before running the test.

Solution

/**
 * This tests validates a PDF document that a business program 
 * has stored as a BLOB into a database.
 */
@Test
public void verifyPDFDataFromDatabase() throws Exception {
  // Arrange:
  int userID = 4711;
  BusinessSystem myBusinessSystem = BusinessSystem.newInstance(userID);

  // Act:
  myBusinessSystem.doSomethingImportantAndWritePDFToDatabase();
  
  // Assert - compare the data of the DB with the data of the original file:
  String referencePdfName = myBusinessSystem.getPDFName();
  InputStream actualPdfFromDB = DBHelper.readPdfFromDB(userID);
  FileInputStream pdfReferenceFromFile = new FileInputStream(referencePdfName);

  AssertThat.document(actualPdfFromDB)
            .and(pdfReferenceFromFile)
            .haveSameText()
            .haveSameAppearance()
  ;

  actualPdfFromDB.close();
  pdfReferenceFromFile.close();
}

This example works with every JDBC database. The complete program is part of the demo project, which can be downloaded from PDFUnit.

Information about DBUnit can be found on the project's homepage.