If JavaScript exists in your PDF documents it is probably important. Often JavaScript plays an active role within document workflows.
PDFUnit's ability to test JavaScript does not replace specialized JavaScript testing tools such as “Google JS Test” , but it is not easy to test the JavaScript in a PDF document using these tools. The following validation methods are provided:
// Methods to validate JavaScript:
.hasJavaScript()
.hasJavaScript().containing(..)
.hasJavaScript().equalsTo(..)
.hasJavaScript().equalsToSource(..)
The following method checks whether a document contains JavaScript at all:
@Test public void hasJavaScript() throws Exception { String filename = "javaScriptClock.pdf"; AssertThat.document(filename) .hasJavaScript() ; }
The expected JavaScript can be read from a file and compared with the JavaScript
in a PDF document. The utility ExtractJavaScript
extracts
JavaScript into a text file, which can then be used for tests:
@Test public void hasJavaScript_ScriptFromFile() throws Exception { String filename = "javaScriptClock.pdf"; File file = new File("javascript/javascriptClock.js"); AssertThat.document(filename) .hasJavaScript() .equalsToSource(file) ; }
The file name parameter can be of type
|
The expected JavaScript need not necessarily be read from a file. It can be passed to the method as a string:
@Test public void hasJavaScript_ComparedToString() throws Exception { String filename = "javaScriptClock.pdf"; String scriptFile = "javascript/javascriptClock.js"; String scriptContent = IOHelper.getContentAsString(scriptFile); AssertThat.document(filename) .hasJavaScript() .equalsTo(scriptContent) ; }
In the previous tests complete JavaScript code was used. But also small parts of a JavaScript code can test:
public void hasJavaScript_ContainingText() throws Exception { String filename = "javaScriptClock.pdf"; String javascriptFunction = "function DoTimers() " + "{ " + " var nCurTime = (new Date()).getTime(); " + " ClockProc(nCurTime); " + " StopWatchProc(nCurTime); " + " CountDownProc(nCurTime); " + " this.dirty = false; " + "}" ; AssertThat.document(filename) .hasJavaScript() .containing(javascriptFunction) ; }
@Test public void hasJavaScript_ContainingText_FunctionNames() throws Exception { String filename = "javaScriptClock.pdf"; AssertThat.document(filename) .hasJavaScript() .containing("StopWatchProc") .containing("SetFldEnable") .containing("DoTimers") .containing("ClockProc") .containing("CountDownProc") .containing("CDEnables") .containing("SWSetEnables") ; }
Whitespaces are ignored when comparing JavaScript.