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); }
Thanks for posting this -- came in handy!
ReplyDeletecan 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
ReplyDeleteTry something like http://blog.jeffdouglas.com/2010/04/28/uploading-an-attachment-using-visualforce-and-a-custom-controller/
DeleteYou want an apex:inputFile and a Apex controller to insert the Attachment.