function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shruthi GM 4Shruthi GM 4 

Test class for the attachment class

How to write test class for this class?


public with sharing class AttachmentUploadController {

  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }

  public PageReference upload() {

    attachment.OwnerId = UserInfo.getUserId();
   // attachment.ParentId = Account.getId; // the record the file is attached to
    attachment.IsPrivate = true;

    try {
      insert attachment;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      return null;
    } finally {
      attachment = new Attachment(); 
    }

    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
  }

}
Best Answer chosen by Shruthi GM 4
YogeshMoreYogeshMore
Hello Shruthi,
 
Use following test class and get 100% coverage.
Let me know if it helps you.
 
@isTest
public class AttachmentUploadController_Test{
    
    // This method to cover valid code
    public static testMethod void first(){        
        
        // Created account record for give the parent id to attachment 
        Account acc = new Account();
        acc.Name = 'TestAcc';
        insert acc;
        
        // Created object of the class
        AttachmentUploadController testObj = new AttachmentUploadController();
        
        // Assigning values to the attachment object
        testObj.attachment.Name = 'TestAttach';
        testObj.attachment.Body = Blob.valueOf('Test Data');
        testObj.attachment.parentId = acc.Id;
        
        // Calling upload method
        testObj.upload();
    }
    
    // This method to throw error and cover catch block
    public static testMethod void second(){        
        AttachmentUploadController testObj = new AttachmentUploadController();
        testObj.upload();
    }
}



Regards,
Yogesh More
more.yogesh422@gmail.com || Skype:-yogesh.more44