Tuesday, October 11, 2011

Inserting an Attachment in a Apex test method

A quick Apex code snippet for inserting an Attachment for use in a testMethod. This can be useful to ensure sufficient code coverage in classes that depend on existing attachments.

     * Create a testing attachment for the opportunity
    private static void addAttachmentToParent(Id parentId) {
    	Blob b = Blob.valueOf('Test Data');
    	Attachment attachment = new Attachment();
    	attachment.ParentId = parentId;
    	attachment.Name = 'Test Attachment for Parent';
    	attachment.Body = b;