+ Start a Discussion
kerryland6kerryland6 

PDF / test insanity?

I've just discovered that if a test calls code that generates a PDF, then the test always passes.

 

Generating a PDF cause code execution to fall into a black hole of success, which is a shame, because sometimes tests are supposed to fail.

 

Here's a test that passes:

 

private class KerryTest {
    class MyException extends Exception {}
    public static testMethod void thisIsCrazy() {

          PageReference pdf = Page.ForgotPassword;       

          Blob pdfBody = pdf.getContentAsPDF();


          throw new MyException('This test should fail!');

    }

}

 

.... it really, really, shouldn't!

 

I know that the docs say I can't call "getContentAsPDF" in a test, which is itself ridiculous, but SURELY it should throw an error, or return an empty PDF, or SOMETHING -- not simply disappear into the ether?

 

Can somebody who knows something explain? I'd love to hear the justification for this behaviour.

 

I've just wasted an awful lot of time figuring out why my test wasn't failing, when I knew it should've been!

 

Thanks

Kerry 

 

 

bob_buzzardbob_buzzard

The Apex Developer's Guide and the Visualforce Developer's Guide both say that getContentAsPDF() can't be used in test methods, though that doesn't quite match up with what you are seeing, in that the call doesn't fail but doesn't provide any useful behaviour either.  There's no more information than that I'm afraid.  

 

From the Apex Developer's Guide:

 

--- snip ---

 

getContentAsPDF

 

Blob

 

Returns the page as a PDF, regardless of the<apex:page> component's renderAs attribute.This method can't be used in:

 

 • Triggers

 • Scheduled Apex

 • Batch jobs

 • Test methods

 • Apex email services

 

--- snip ---

kerryland6kerryland6

The problem with the "cant be used in test methods" escape clause is that it means you can't test any code that, even as a byproduct, produces a PDF, and that's simply absurd.

 

What it means is that every piece of code that generates a PDF has to be surrounded by a check for  !Test.isRunningTest(). Something like:

 

    Blob pdfBody;

    if (!Test.isRunningTest()) {

         pdfBody = pdf.getContentAsPDF();

    }

 

I'm getting used to Salesforce's frightening number of arbitrary restrictions, but this one boggles my mind.

 

At some point you have to stop "fixing" problems with documentation, and instead actually fix the problems.

 

Am I alone in this sentiment?

 

Are there actual Salesforce development staff on these boards, or is it just a team of end users supporting each other?

 

Thanks

Kerry

Larry LeonidasLarry Leonidas

Agreed, we are unable to test on ContentVersion due to similar issues with generating test scenarios.