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
salesforcerrrsalesforcerrr 

Test class for Attachment Controller

Hi, 

I am getting 25% coverage for below test class. I also copied the controller. Could someone assist with this please? Much appreciated. 
 
Public Class CaseImageController {

    String recId;
    
    public CaseImageController (ApexPages.StandardController controller) {
        recId = controller.getId();    
    }
    
    public String getFileId() {
        String fileId = '';
        List<Attachment> attachedFiles = [select Id from Attachment where parentId =:recId order By LastModifiedDate DESC limit 1];
        if( attachedFiles != null && attachedFiles.size() > 0 ) {
            fileId = attachedFiles[0].Id;
        }
        return fileId;    
    }
}
 
@isTest
private class TestImageControllerTest{

      static testMethod void testAttachments()
    {
        Case cc=new Case(Subject='Acme Inc');
        insert cc;
        CaseImageController controller=new CaseImageController(new ApexPages.StandardController(cc));
 
        Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=cc.id;
        insert attach;
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:cc.id];
        System.assertEquals(1, attachments.size());
    }
}

 
Best Answer chosen by salesforcerrr
PawanKumarPawanKumar
Please use below test class and let me know if it works for you. Please see the change in Bold.

--------------------------------------
@isTest
private class TestImageControllerTest {

 static testMethod void testAttachments() {
  Case cc = new Case(Subject = 'Acme Inc');
  insert cc;
  CaseImageController controller = new CaseImageController(new ApexPages.StandardController(cc));

  Attachment attach = new Attachment();
  attach.Name = 'Test';
  Blob bodyBlob = Blob.valueOf('Testing Body of Attachment');
  attach.body = bodyBlob;
  attach.parentId = cc.id;
  insert attach;

  List < Attachment > attachments = [select id, name from Attachment where parent.id = : cc.id];
  System.assertEquals(1, attachments.size());
  
  // call your getFileId() to get code coverage
  String newAttachId = controller.getFileId();
  System.assertEquals(newAttachId, attachments[0].Id);

  
 }
}
------------------------------------------

Regards,
Pawan Kumar