Monday, October 7, 2013

Writing Apex Test method for insert attachment





Salesforce.com makes it extremely easy to add attachments to any record either programmatically or from the UI. Writing a test case for the insert attachment is little tricky. Below are the quick apex code snippets for inserting an attachment for use in a Apex Text method. This would be useful for ensuring sufficient code coverage for the Apex classes that depend on insert attachment functionality. 

Version 1: with 1 argument (object Id of an object to which the attachment is added or the parentId of the attachment)

    /**
     * test method for add attachment to any object by passing the object Id
     */
    private static void testAddAttachmentToObject(Id objectId) {
    Blob b = Blob.valueOf('Test Data');
   
    Attachment attachment = new Attachment();
    attachment.ParentId = objectId;
    attachment.Name = 'Test Attachment for Parent';
    attachment.Body = b;
   
    insert(attachment);

     List<Attachment> attachments=[select id, name from Attachment where parent.id=: objectId];
     System.assertEquals(1, attachments.size());
    }

Version 2: without any arguments

    /**
     * test method for add attachment to any object by creating an object 
     */
    private static void testAddAttachmentToObject() {

        Account acct = new Account(Name='Test Account'); 
       /*
            you should supply values for all mandatory fields 
            same way, you can create any other object
      */
        insert acct;

     Blob b = Blob.valueOf('Test Data');
      
     Attachment attachment = new Attachment();
     attachment.ParentId = acct.Id;
     attachment.Name = 'Test Attachment for Parent';
     attachment.Body = b;
    
     insert(attachment);

     List<Attachment> attachments=[select id, name from Attachment where parent.id=: acct.Id];
     System.assertEquals(1, attachments.size());
    }

Hope this is helpful.