+ Start a Discussion
Sai Subhash 6Sai Subhash 6 

Can any one tell me how to write test class for below code?

public class UploadAttachments
{
   @AuraEnabled
    public static Id saveChunk(Id parentId, String fileName, String base64Data, String contentType, String fileId) {
        // check if fileId id ''(Always blank in first chunk), then call the saveTheFile method,
        //  which is save the check data and return the attachemnt Id after insert, 
        //  next time (in else) we are call the appentTOFile() method
        //   for update the attachment with reamins chunks   
        if (fileId == '') {
            fileId = saveTheFile(parentId, fileName, base64Data, contentType);
        } else {
            appendToFile(fileId, base64Data);
        }
 
        return Id.valueOf(fileId);
    }
 
    public static Id saveTheFile(Id parentId, String fileName, String base64Data, String contentType) {
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        
        Attachment oAttachment = new Attachment();
        oAttachment.parentId = parentId;
 
        oAttachment.Body = EncodingUtil.base64Decode(base64Data);
        oAttachment.Name = fileName;
        oAttachment.ContentType = contentType;

        insert oAttachment;
 
        return oAttachment.Id;
    }
 
    private static void appendToFile(Id fileId, String base64Data) {
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
 
        Attachment a = [
            SELECT Id, Body
            FROM Attachment
            WHERE Id =: fileId
        ];
 
        String existingBody = EncodingUtil.base64Encode(a.Body);
 
        a.Body = EncodingUtil.base64Decode(existingBody + base64Data);
 
        update a;
    }
    
    @AuraEnabled
    public static String return_account()
     {
         Schema.DescribeSObjectResult result = account.SObjectType.getDescribe();
         String objectIdPrefix = result.getKeyPrefix();
         
         String returnprtab ='/'+objectIdPrefix+'/o';
         
      
         return returnprtab;
     } 
}
Best Answer chosen by Sai Subhash 6
Sampath SuranjiSampath Suranji
Hi Sai,
Please try below code, 
@isTest
public class UploadAttachmentsTest {
    
    public static testmethod void  saveChunk(){
        contact objContact =  new Contact(lastName='test contact');
        insert objContact ;
        
        blob file=  Blob.valueOf('sample text');
        Attachment objAttachment=new Attachment(); 
        objAttachment.Body= file;
        objAttachment.Name = 'test Attachment';
        objAttachment.ParentId = objContact.Id;
        insert objAttachment;
        
        UploadAttachments.saveChunk(objContact.id,'testAttachment',file.toString(),'jpg',objAttachment.Id);
        UploadAttachments.saveChunk(objContact.id,'testAttachment',file.toString(),'jpg','');
    }
    
    public static testmethod void  return_account(){
        UploadAttachments.return_account();
    }
    
}

Regards