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
LudivineLudivine 

Test class for upload attachment VF page

Hi,

I have created a Visualforce Page to be able to upload attachment in Salesforce for X-Author application since Salesforce doesn't allow anymore to create any attachments in attachment object.
Everything is working as expected. I just need help to get full code coverage.
Only 47% with the test cIass I wrote. Could you tell me why I am not able to cover it all and what is wrong?
 
//VF Page :
<apex:page standardController="Apttus_XApps__Application__c" extensions="AttachmentUploadController">
  <apex:form >
      <apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
       </apex:pageBlock>
  </apex:form>
</apex:page>

//Controller :
public with Sharing class AttachmentUploadController {

    public Id recId
    {    get;set;    }
    
    public AttachmentUploadController(ApexPages.StandardController ctlr)
    {
       recId = ApexPages.CurrentPage().getParameters().get('Id');      
    }
    
    public string fileName 
    {    get;set;    }
    
    public Blob fileBody 
    {    get;set;    }
  
    public PageReference UploadFile()
    {    
        PageReference pr;
        if(fileBody != null && fileName != null)
        {
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
            
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }    
}


// Test method:
@isTest
public class AttachmentUploadController_Test{

    static testMethod void testCase1() {        
        Id recID;    
    PageReference pr;
        String filename = 'Att1';
        Blob Body = Blob.valueof('Unit Test Attachment Body');

        Apttus_XApps__Application__c objApp = New Apttus_XApps__Application__c();
        objApp.Name = 'Test Upload Attachment';
        objApp.Apttus_XApps__Activated__c = True;
        objApp.Apttus_XApps__UniqueId__c ='123ADCDEFG';
        insert objApp;
        
        recID = objApp.Id;      
        
        AttachmentUploadController controller=new AttachmentUploadController(new ApexPages.StandardController(objApp));        
        
        Attachment myAttachment =New attachment();
        myAttachment.name =filename;
        myAttachment.Body = Body;
        myAttachment.ParentId = recID;
        controller.UploadFile();        

    }      
          
}
In the Developer console I see that this lines of the controller are not covered :

- public string fileName

-   Attachment myAttachment  = new Attachment();
    myAttachment.Body = fileBody;
    myAttachment.Name = fileName;
    myAttachment.ParentId = recId;
    insert myAttachment;
                        
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;

Thank you.
Ludivine
Best Answer chosen by Ludivine
Bryan TelfordBryan Telford
You have to set the controller propereties. Also. it's a good idea to add Test.startTest() and Test.stopTest() to your test class.

Try modifying your code with this:

Test.startTest();
controller.fileName = 'Test File';
controller.fileBody = Blob.valueOf('Unit Test Attachment Body');
controller.Upload();
Test.stopTest();

All Answers

Bryan TelfordBryan Telford
You have to set the controller propereties. Also. it's a good idea to add Test.startTest() and Test.stopTest() to your test class.

Try modifying your code with this:

Test.startTest();
controller.fileName = 'Test File';
controller.fileBody = Blob.valueOf('Unit Test Attachment Body');
controller.Upload();
Test.stopTest();
This was selected as the best answer
LudivineLudivine
Hi Bryan,

Thank you it works!! I have now 82% code coverage ,I just changed Upload() by UploadFile().

May I ask you to help me to cover the PageReference  part? 
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;

I have written these lines, however it doesn't seem to work :
     
Test.startTest();  
           PageReference pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           Return pr;
    Test.stopTest();   

Thanks!!
Bryan TelfordBryan Telford
You don't have to explicity test the PageReference. I refactored your test class. It now has 100% coverage. I set your controller property for recID to the parent id of the record. Also, I added another method to verify your return null (basically, if fileName and fileBody are not provided). Note: I substituted your custom object with Account.

@isTest
public class AttachmentUploadController_Test{

    static testMethod void verifyUploadFileReturnsAttachment() {        
        
        String filename = 'Att1';
        Blob Body = Blob.valueof('Unit Test Attachment Body');

        Account objApp = New Account();
        objApp.Name = 'Test Upload Attachment';
        insert objApp;
                
        AttachmentUploadController controller=new AttachmentUploadController(new ApexPages.StandardController(objApp));        
        
        Test.startTest();
        controller.fileName = 'Test File';
        controller.recID = objApp.Id;      
        controller.fileBody = Blob.valueOf('Unit Test Attachment Body');
        controller.UploadFile();    
        Test.stopTest();
        
        Attachment [] att = [SELECT Id, ParentId from Attachment where ParentId = :objApp.id];
        System.assertEquals(att.size(), 1);

    }      
     
    static testMethod void verifyUploadFileReturnsNull() {        

        Account objApp = New Account();
        objApp.Name = 'Test Upload Attachment';
        insert objApp;
                
        AttachmentUploadController controller=new AttachmentUploadController(new ApexPages.StandardController(objApp));                
        Test.startTest();
        controller.UploadFile();     
        Test.stopTest();
        
        Attachment [] att = [SELECT Id, ParentId from Attachment where ParentId = :objApp.id];
        System.assertEquals(att.size(), 0);

    }       
}
LudivineLudivine
Hi Bryan,

Many thanks and for all your clear explanation, it works perfectly in the sandbox, now I have implemented it in production and it behaves differently .
When I click on the Upload button on my VF page, the current page is showing with the header ( ie.with my name at the top right), inside the VF section... I  need to refresh the page to get it back to normal. Do you know which settings is different in production?
Thank you!
Wish you a nice day.
Bryan TelfordBryan Telford
I'm not aware of any inherent difference between sandbox and production with this code. Can you post a screen shot?
LudivineLudivine
Hi Bryan,

Fixed! I have remove the return pr statement, actually I did not need to show the attachment in my section as I have another related list Notes and Attachments in my page Layout .
Now with this section upload attachments, I click on the button, I upload my attachment, and this attachment is showing in the other section Notes and Attachment below (after refreshing the page). So all good so far!
Thank you very much to help me solve this issue so quickly, very much appreciate!
I wish you a nice day.
Ludivine