If you have created an Apex class which uses Attachments in some way you might need to create Attachments as test data for the testMethod in order to get the coverage to be able to deploy.
The attachment has three required fields:
Body,
Name and
ParentIdBut how is the body, which is the attachment, created programmatically?
I found this solution in a Salesforce community and also later on the Salesforce blog:
PageReference pdf = Page.testPDF; pdf.getParameters().put('p','p'); pdf.setRedirect(true); // Grab the PDF! Blob b = pdf.getContent(); // Create and insert attachment Attachment attachment = new Attachment(Name='An attachment',body=b,parentId=accId); insert attachment; |
The above assumes that you have a valid accountId 'accId' serving as the parent of the attachment and that you have created a Visualforce page 'testPDF' which is rendered as PDF. Could look like this:
<apex:page renderas="pdf"> <!-- Begin Default Content REMOVE THIS --> <h1>Congratulations</h1> This is your new Page <!-- End Default Content REMOVE THIS --> </apex:page> |