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;
    	
    	insert(attachment);
    }

3 comments:

  1. Thanks for posting this -- came in handy!

    ReplyDelete
  2. can i get apex page sample to call this? i am intend to add attachment to custom object. if you have any sample please share to gspandian@gmail.com

    ReplyDelete
    Replies
    1. Try something like http://blog.jeffdouglas.com/2010/04/28/uploading-an-attachment-using-visualforce-and-a-custom-controller/

      You want an apex:inputFile and a Apex controller to insert the Attachment.

      Delete