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
Tiffany Shabazz 9Tiffany Shabazz 9 

Need help writing test class to cover code

Hi - I am using the following code to allow users to upload documents on a new custom object. I am having issues developing the test to cover it as it is apparently only covering 6%. Any help is greatly appreciated. Here is what I have so far:

Code:

public class UploadAttachmentControllerReviews {
    
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String description {get;set;}
    private Opportunity opportunity {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public UploadAttachmentControllerReviews(ApexPages.StandardController controller) { 
        this.opportunity = (Opportunity)controller.getRecord();
    }   
    
    // creates a new Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Business_Reviews__c obj = new Business_Reviews__c();
        obj.opportunity__c = opportunity.Id; 
        obj.description__c = description;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Attachment__c record
    *  2. Insert new Attachment with the new Business_Reviews__c record as parent
    *  3. Update the Attachment__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
                Business_Reviews__c customAttachment = [select id from Business_Reviews__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+opportunity.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+opportunity.Id);
    }     

}

Test:

@isTest 
public class ExtensionTestActivityClass 
{
 static testMethod void testMethod1() 
 {
 Account testAccount = new Account();
 testAccount.Name='Test Account';
 insert testAccount;

 Test.StartTest(); 
  ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
  UploadAttachmentControllerActivity testOppPlan = new UploadAttachmentControllerActivity(sc);

  PageReference pageRef = Page.Cross_Selling_Activity_Page; // Add your VF page Name here
  pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
  Test.setCurrentPage(pageRef);
  
  //testOppPlan.save(); //call all your function here
  // creates a new Attachment__c record
        Cross_Selling_Activity__c obj = new Cross_Selling_Activity__c();
        obj.account__c = obj.Id; 
        obj.description__c = 'test';
        }
    
    // create an actual Attachment record with the Attachment__c as parent
    private Database.SaveResult saveStandardAttachment; {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.name = 'this.fileName';
        attachment.parentId = attachment.id;
        // inser the attahcment
        result = Database.insert(attachment);    
 Test.StopTest();
  }
  }
Amit Chaudhary 8Amit Chaudhary 8

Please try below code
@isTest 
public class ExtensionTestActivityClass 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account';
		insert testAccount;

		Opportunity opp1 = new Opportunity (Name='Opp1', StageName='Prospecting', CloseDate=Date.today(), AccountId = acc.id);
		insert opp1;

		
		Test.StartTest(); 
		
			ApexPages.StandardController sc = new ApexPages.StandardController(opp1);
			UploadAttachmentControllerActivity testOppPlan = new UploadAttachmentControllerActivity(sc);

			PageReference pageRef = Page.Cross_Selling_Activity_Page; // Add your VF page Name here
			pageRef.getParameters().put('id', String.valueOf(opp1.Id));
			Test.setCurrentPage(pageRef);
			
			testOppPlan.description ='Test';
			testOppPlan.back();
			try
			{
				testOppPlan.processUpload();
			}Catch(Exception ee)
			{}	

		Test.StopTest();
	}
}

Let us know if this will help you
 
Tiffany Shabazz 9Tiffany Shabazz 9
Hi Amit - Thanks for your response. I am now getting this error: Variable does not exist: acc.id. Do you know what might be causing this?
Amit Chaudhary 8Amit Chaudhary 8
try below code
@isTest 
public class ExtensionTestActivityClass 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account';
		insert testAccount;

		Opportunity opp1 = new Opportunity (Name='Opp1', StageName='Prospecting', CloseDate=Date.today(), AccountId = testAccount.id);
		insert opp1;

		
		Test.StartTest(); 
		
			ApexPages.StandardController sc = new ApexPages.StandardController(opp1);
			UploadAttachmentControllerActivity testOppPlan = new UploadAttachmentControllerActivity(sc);

			PageReference pageRef = Page.Cross_Selling_Activity_Page; // Add your VF page Name here
			pageRef.getParameters().put('id', String.valueOf(opp1.Id));
			Test.setCurrentPage(pageRef);
			
			testOppPlan.description ='Test';
			testOppPlan.back();
			try
			{
				testOppPlan.processUpload();
			}Catch(Exception ee)
			{}	

		Test.StopTest();
	}
}

Let us know if this will help you
 
Tiffany Shabazz 9Tiffany Shabazz 9
Now I am receiving this error when executing the test: System.TypeException: Invalid conversion from runtime type Opportunity to Account. 
Tiffany Shabazz 9Tiffany Shabazz 9
Here are the details from the Log: 

User-added image
Amit Chaudhary 8Amit Chaudhary 8
Can you please post Apex class and test class which you are using ?

If you want i can lookinto your org please email me amit.salesforce21@gmail.com
Tiffany Shabazz 9Tiffany Shabazz 9
Hi Amit,

I was able to get it working and it looks like it is at 63% code coverage so we are getting there! Below is the apex class that corresponds to the test. Is there anything else I can add to get it to the required 75% coverage? Thanks!

public class UploadAttachmentControllerImplementation {
    
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String description {get;set;}
    private Opportunity opportunity {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public UploadAttachmentControllerImplementation(ApexPages.StandardController controller) { 
        this.opportunity = (Opportunity)controller.getRecord();
    }   
    
    // creates a new Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Implementation__c obj = new Implementation__c();
        obj.opportunity__c = opportunity.Id; 
        obj.description__c = description;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Attachment__c record
    *  2. Insert new Attachment with the new Implementation__c record as parent
    *  3. Update the Attachment__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
                Implementation__c customAttachment = [select id from Implementation__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+opportunity.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+opportunity.Id);
    }     

}