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
wcwill978wcwill978 

Test Class for Controller Low Code Coverage

Hi, I have a class for a VF page that is used to attach files into a custom object off the account. I would like some help creating a test class for the class that would give a higher code coverage. Currently im only getting 6% code coverage. Below is what I have, thank you:

Class:
public class AttachController {
    
    public String name {get;set;}
    //public Boolean selectedAwesomeness {get;set;}
    public String description {get;set;}
    private Account account {get;set;} 
    public String salesAttachmentName {get;set;}
    public Blob fileBody {get;set;}
    
    public UploadAttachmentController(ApexPages.StandardController controller) { 
        this.account = (Account)controller.getRecord();
    }   
    
    // creates a new Sales_Attachments__c record
    private Database.SaveResult saveCustomAttachment() {
        Sales_Attachments__c obj = new Sales_Attachments__c();
        obj.Account__c = account.Id; 
        obj.Description__c = description;
        obj.Attachment_Name__c = name;
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Sales_Attachments__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.salesAttachmentName;
        attachment.parentId = parentId;
        result = Database.insert(attachment);
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Sales_Attachments__c record
    *  2. Insert new Attachment with the new Sales_Attachments__c record as parent
    *  3. Update the Sales_Attachments__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
        try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }
        
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
        
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));            
                return null;
            } else {
                // update the custom attachment record with some attachment info
                Sales_Attachments__c customAttachment = [select id from Sales_Attachments__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.salesAttachmentName;
                customAttachment.Attachment_ID__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+account.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+account.Id);
    }     

}

VF Page:
<apex:page standardController="Account" tabStyle="Account" extensions="AttachController">

 <apex:sectionHeader title="{!Account.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >

 <apex:pageBlockButtons >
   <apex:commandButton action="{!back}" value="Back"/>
   <apex:commandButton action="{!back}" value="Cancel"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Name" for="name"/> 
      <apex:inputTextarea id="name" value="{!name}" rows="1" cols="30"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!salesAttachmentName}"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Description" for="description"/> 
      <apex:inputTextarea id="description" value="{!description}" rows="4" cols="50"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem>    
    
  </apex:pageBlockSection>
 
 </apex:pageBlock>


 </apex:form>

</apex:page>

Test Class:
@isTest
private class AttachTest {

    static testMethod void testUploadAttachmentController(){
    //Create test Sys Admin User to Run As
    Profile prof = [select id from profile where name='System Administrator'];

    User u1 = new User();
      u1.alias = 'alias3';
      u1.email ='testuser@email3.com';
      u1.emailencodingkey ='UTF-8';
      u1.lastname = 'userLast';
      u1.languagelocalekey ='en_US';  
      u1.localesidkey ='en_US';
      u1.profileid = prof.Id;
      u1.timezonesidkey ='America/Los_Angeles';
      u1.username ='testuser@email3.com';  

    insert u1;
    System.runAs(u1){  
    
        //Create Account
        List <Account> acctList = new List<Account>();
        acctList.add(new Account(Name='Acct1', Industry = 'Commercial'));
        acctList.add(new Account(Name='Acct2', Industry = 'Retail'));
        insert acctList;
        
        //New Sales_Attachments__c record where the actual SFDC child attachment will be added to.
        Sales_Attachments__c salesAttach = new Sales_Attachments__c();     
        salesAttach.Name = 'File1Test';
        salesAttach.Account__c = acctList[0].id;
        salesAttach.Description__c = '1234TEST';
        insert salesAttach;
        
        Sales_Attachments__c newSA = [SELECT ID, Name, Description__c FROM Sales_Attachments__c  WHERE ID = :salesAttach.ID];
        System.AssertEquals('1234TEST',newSA.Description__c);
            
       
        //Upload new attachment under the Sales_Attachments__c record
        Attachment attach = new Attachment();     
        attach.Name = 'Unit Test Attachment';
        Blob bodyBlob = Blob.valueOf('Unit Test Attachment Body');
        attach.body = bodyBlob;
        attach.ParentId = salesAttach.id;
        insert attach;
        
        salesAttach.Name = attach.Name;
        salesAttach.Attachment_ID__c = attach.Id;
        
        update salesAttach;
        
        Sales_Attachments__c testSA = [SELECT ID, Name FROM Sales_Attachments__c WHERE ID = :salesAttach.ID];
        System.AssertEquals('Unit Test Attachment',testSA.Name);
        
       
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:salesAttach.id];
        System.assertEquals(1, attachments.size());
        
        ApexPages.StandardController sc = new ApexPages.StandardController(acctList[0]);
        UploadAttachmentController upload = new UploadAttachmentController(sc);
        
        PageReference pageRef = Page.UploadAttachment;
        pageRef.getParameters().put('id', String.valueOf(acctList[0].Id));
        Test.setCurrentPage(pageRef);
        
        System.assertEquals(attach.Name, attach.Name);
        
        }
    }
}



 
ManojjenaManojjena
HI wcwill978,

I saw few problem in your code which may result like .Try to modify your code little bit .
AttachController  is your extension name,however your constructor name is UploadAttachmentController .try to rename in both class and test class as AttachController  . Let me know if it helps !!
Thanks
Manoj
wcwill978wcwill978
Hi Manoj,

thank you, I made the change. Just ran the test, but only getting 10% coverage.