function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Churchill19Churchill19 

Visualforce pdf to save as attachment on a record

Hi,

I have a button that once clicked it call for visualforce page to render as pdf and save it to a record which works in the sandbox...
i am trying to write test scrip for the following code but not sure how to.... can anyone start me off?

here is my button
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 

{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 

/* call class and pass through parameters */ 

var ref = "{!Sales_Quality_Assessments__c.Id}"; 

var result = sforce.apex.execute("PdfGeneratorControllerTest1","savePdf1",{parentId:"{!Sales_Quality_Assessments__c.Id}"}); 



window.open('/apex/FormTest?scontrolCaching=1&id='+ref+'&scontrolCaching=1');
and for the class: - 
 
global class PdfGeneratorControllerTest1 {

  
  webservice static void savePdf1(string parentId) {

    PageReference pdf = Page.FormTest;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',parentId);
    // create the new attachment
    Attachment attach = new Attachment();
    
    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getContentAsPDF();

    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body = Blob.valueOf('Error...');
    }

    attach.Body = body;
    // add the user entered name pdf.getContentAsPDF    
    attach.Name = 'Coaching Form'+parentid;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = parentId;
    attach.ContentType = 'application/pdf';
    
    insert attach;

    // send the user to the account to view results
    // return Apexpages.currentPage();
    // return new PageReference('/'+parentId);

    //   return Apexpages.currentPage();

  }

}
thanks....

 
Hargobind_SinghHargobind_Singh
I dont think getContentAsPDF is supported in test class. You can try to have an IF clause on line 18, such as:
 
if(Test.isRunningTest()){
 body = Blob.getValueOf('abcd'); 
}
else{ 
 body = pdf.getContentAsPDF();
}