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
benwrigleybenwrigley 

Cannot test PDF generation

Hi All,

 

I have a VF page set up to render as PDF. I also have a class that calls this page, stores in a blob and attaches to an Opportunity.  This all works fine.

 

My test scripts fail however on this line:

 

Blob pdfBlob = pdfPage.getContent();

 

with 'List has no rows for assignment to SObject'.

 

here is the context:

 

 

public void generateSalesOrder() {
		
        PageReference pdfPage = Page.TMDR_SalesOrder;
        pdfPage.getParameters().put('oppid',Opp.id);
        
        // generate the pdf blob
        Blob pdfBlob = pdfPage.getContent();
        String attName = Opp.name + '.pdf';
        
        //does the quote exist already?
        List<Attachment> atts = [select ID from Attachment where parentId = :Opp.id and name=:attName];
        
        if (atts.size() > 0){
        	for (Attachment att:atts){
        		delete att;
        	}
        }
        
        PDF = new Attachment(parentId = Opp.id, name=attName, body = pdfBlob);
        insert PDF;
        
  }

 

 

I wondered if actually the error was coming from the VF page itself, so I stripped out all of it's content, but still got the same error.

 

Anyone got any advice?

 

TIA

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You can't execute getContent() in a test method - the apex docs state:

 

--- snip ---

 

 

This method can't be used in:
• Triggers
• Scheduled Apex
• Batch jobs
• Test methods

This method can't be used in:• Triggers• Scheduled Apex• Batch jobs• Test methods

 

 

--- snip ---

 

I usually do something along these lines to allow the code to run for unit tests:

 

 

Blob content;
if (Test.IsRunningTest())
{
   content=Blob.valueOf('UNIT.TEST');
}
else
{
   content=pr.getContent();
}

 

 

All Answers

bob_buzzardbob_buzzard

You can't execute getContent() in a test method - the apex docs state:

 

--- snip ---

 

 

This method can't be used in:
• Triggers
• Scheduled Apex
• Batch jobs
• Test methods

This method can't be used in:• Triggers• Scheduled Apex• Batch jobs• Test methods

 

 

--- snip ---

 

I usually do something along these lines to allow the code to run for unit tests:

 

 

Blob content;
if (Test.IsRunningTest())
{
   content=Blob.valueOf('UNIT.TEST');
}
else
{
   content=pr.getContent();
}

 

 

This was selected as the best answer
benwrigleybenwrigley

Thanks Bob,

 

Brilliant as always!