6.12.  Caching Test Documents

Initial Situation

You have many tests - that is good.

Problem

The tests are running slowly - that is bad.

Solution Approach

Maybe it's because the PDF documents are very large, but after all it has to be tested. Instantiate the test document only once for all tests in a class.

Solution

public class CachedDocumentTestDemo {

  private static DocumentValidator document;

  @BeforeClass  // Document will be instantiated once for all tests:
  public static void loadTestDocument() throws Exception {
    String filename = "documentUnderTest.pdf";
    document = AssertThat.document(filename);
  }
  
  @Test
  public void test1() throws Exception {
    document.hasNumberOfBookmarks(4);
  }
  
  // ... and more tests.

}

Of course, you can concatenate all test methods in one statement. But how would you name the test? Names of test methods should reflect the content as exactly as possible. Otherwise, a test report with many hundreds of tests is difficult to understand. So, testAll is a bad name - it means nothing.

PDFUnit is stateless. But it can not be guaranteed that 3rd-party libraries are also stateless. So, if you have problems with tests using cached documents, change the annotation @BeforeClass into @Before, remove the modifier static and the PDF document is instantiated for each test method:

@Before  // Document will be instantiated for each test. No caching:
public void loadTestDocument() throws Exception {
  String filename = "documentUnderTest.pdf";
  document = AssertThat.document(filename);
}