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
Shravan Kumar 71Shravan Kumar 71 

Controller Extension Test Class

Please help me with the Test Class for the below Controller :

public class ActivitySearchController {
    
    Public List<Task> TaskList {get;set;}  
    String currentId =ApexPages.CurrentPage().getparameters().get('id');
                
    public ActivitySearchController(ApexPages.StandardController controller) {    
        //Lead ID
        if (currentId.startsWith('00Q')) {
            
            try{         
                List <Lead> leadList = [SELECT id, Email, Alternate_Email__c FROM Lead WHERE ID=:currentId];
                String ldEmail       = leadList[0].Email;
                String ldAltEmail    = leadList[0].Alternate_Email__c;
                Set<String> emailIds = new Set<string>();
                if(ldEmail!=null){
                    emailIds.add(ldEmail);
                }
                if(ldAltEmail!=null){
                    emailIds.add(ldAltEmail);
                }
                
                List <Lead> rldLead    = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
                List <Account> accLst  = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
                
                Set<Id> leadID = new Set<Id>(); 
                Set<Id> accIds = new Set<Id>();    
                for(Lead lE : rldLead){
                    leadID.add(lE.id);            
                }  
                for(Account acc : accLst){
                    accIds.add(acc.id);            
                }      
                
                TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task 
                            WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC];
                
                if(TaskList.size() == 0)
                {
                    Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
                } 
                
            } 
            
            catch(Exception e){
                system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
            }
            
        }
        
        
        //Account ID
        else if (currentId.startsWith('001p')) {
            
            try{         
                List <Account> accList = [SELECT id, PersonEmail, Alternate_Email__c FROM Account WHERE ID=:currentId];
                String ldEmail       = accList[0].PersonEmail;
                String ldAltEmail    = accList[0].Alternate_Email__c;
                Set<String> emailIds = new Set<string>();
                if(ldEmail!=null){
                    emailIds.add(ldEmail);
                }
                if(ldAltEmail!=null){
                    emailIds.add(ldAltEmail);
                }
                
                List <Lead> rldLead    = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
                List <Account> accLst  = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
                
                Set<Id> leadID = new Set<Id>(); 
                Set<Id> accIds = new Set<Id>();    
                for(Lead lE : rldLead){
                    leadID.add(lE.id);            
                }  
                for(Account acc : accLst){
                    accIds.add(acc.id);            
                }      
                
                TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task 
                            WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC LIMIT 10];
                
                if(TaskList.size() == 0)
                {
                    Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
                } 
                
            } 
            
            catch(Exception e){
                system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
            }
            
        }
        
        //Opportunity ID
        else if (currentId.startsWith('006p')) {
            
            try{         
                List <Opportunity> oppList = [SELECT id, AccountId FROM Opportunity WHERE ID=:currentId];
                String oppID = oppList[0].Accountid;
                List <Account> oppAccList = [SELECT id, PersonEmail, Alternate_Email__c FROM Account WHERE ID =: oppID];
                String ldEmail       = oppAccList[0].PersonEmail;
                String ldAltEmail    = oppAccList[0].Alternate_Email__c;
                Set<String> emailIds = new Set<string>();
                if(ldEmail!=null){
                    emailIds.add(ldEmail);
                }
                if(ldAltEmail!=null){
                    emailIds.add(ldAltEmail);
                }
                
                List <Lead> rldLead    = [SELECT id, Email, Alternate_Email__c FROM Lead Where Email IN:emailIds OR Alternate_Email__c IN:emailIds];
                List <Account> accLst  = [SELECT id, PersonEmail, Alternate_Email__c FROM Account Where PersonEmail IN:emailIds OR Alternate_Email__c IN:emailIds];
                
                Set<Id> leadID = new Set<Id>(); 
                Set<Id> accIds = new Set<Id>();    
                for(Lead lE : rldLead){
                    leadID.add(lE.id);            
                }  
                for(Account acc : accLst){
                    accIds.add(acc.id);            
                }      
                
                TaskList = [Select id, Subject, Comments_Short__c, who.Type, What.Type, Priority, Status, ActivityDate FROM Task 
                            WHERE (accountid IN:accIds OR whoId IN:leadID) AND Status = 'Open' ORDER BY createddate DESC LIMIT 10];
                
                if(TaskList.size() == 0)
                {
                    Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
                } 
                
            } 
            
            catch(Exception e){
                system.debug('getlinenumber-->'+ e.getMessage() +' line '+ e.getLineNumber());
            }
            
        }
    }
}
Best Answer chosen by Shravan Kumar 71
Steven NsubugaSteven Nsubuga
Those line can only be covered when there are no tasks that meet the criteria being queried for.
Same thing goes for the exception,  however, given the relative simplicity of the code I see no reason to have the code within try and catch blocks.
I suggest you get rid of the catch block unless you know a way or scenario in which an exception would be thrown, and if so, you can edit the tests to be able to test that scenario.

For the no tasks scenario, see updated test class below. I have created an additional NoTasks test method for each scenario
@isTest
private class ActivitySearchControllerTest {
    
    @testSetup static void methodName() {
		
		Account testAccount = new Account (name='Test', PersonEmail = 'em@test.com', Alternate_Email__c = 'testa@test.com');
        insert testAccount;
		
		Lead ld = new Lead(Company = 'Lead Company', FirstName = 'TestF', LastName = 'TestN', Email = 'em@test.com', Alternate_Email__c = 'testb@test.com');
        insert ld;
		
		Opportunity testOpportunity = new Opportunity(
            Name = 'Test Opportunity',
			AccountId = testAccount.Id,
            CloseDate = date.today().addDays(45),         
            StageName = 'Negotiating',
            
        );
        insert testOpportunity;
		
		Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Open',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
								   Comments_Short__c = 'something'
                                   WhoId = ld.Id);
		insert newTask;						   
       
	}
	
	@isTest static  void testWithAccount() {        
        Account testAccount = [SELECT id FROM Account LIMIT 1];
        
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(testAccount.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(testAccount);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithAccountNoTasks() {        
		
		Account otherAccount = new Account (name='Test', PersonEmail = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherAccount;
		
		Lead otherLead = new Lead(Company = 'Other Company', FirstName = 'Other', LastName = 'Lead', Email = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherLead;
		
		        
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(otherAccount.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(otherAccount);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithLead() {        
        Lead ld = [SELECT id FROM Lead LIMIT 1];
		
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(ld.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(ld);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithLeadNoTasks() {        
        Lead otherLead = new Lead(Company = 'Other Company', FirstName = 'Other', LastName = 'Lead', Email = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherLead;
		
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(otherLead.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(otherLead);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithOpportunity() {        
        
		Opportunity testOpportunity = SELECT id FROM Opportunity LIMIT 1];

		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(testOpportunity.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(testOpportunity);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithOpportunityNoTasks() {        
        
		Account otherAccount = new Account (name='Test', PersonEmail = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherAccount;
		
		Opportunity otherOpportunity = new Opportunity(
            Name = 'Test Opportunity',
			AccountId = otherAccount.Id,
            CloseDate = date.today().addDays(45),         
            StageName = 'Negotiating',
            
        );
		
		Lead otherLead = new Lead(Company = 'Other Company', FirstName = 'Other', LastName = 'Lead', Email = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherLead;

		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(otherOpportunity.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(otherOpportunity);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
}

 

All Answers

Steven NsubugaSteven Nsubuga
Try this
@isTest
private class ActivitySearchControllerTest {
    
    @testSetup static void methodName() {
		
		Account testAccount = new Account (name='Test', PersonEmail = 'em@test.com', Alternate_Email__c = 'testa@test.com');
        insert testAccount;
		
		Lead ld = new Lead(Company = 'Lead Company', FirstName = 'TestF', LastName = 'TestN', Email = 'em@test.com', Alternate_Email__c = 'testb@test.com');
        insert ld;
		
		Opportunity testOpportunity = new Opportunity(
            Name = 'Test Opportunity',
			AccountId = testAccount.Id,
            CloseDate = date.today().addDays(45),         
            StageName = 'Negotiating',
            
        );
        insert testOpportunity;
		
		Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
								   Comments_Short__c = 'something'
                                   WhoId = ld.Id);
		insert newTask;						   
       
	}
	
	@isTest static  void testWithAccount() {        
        Account testAccount = [SELECT id FROM Account LIMIT 1];
        
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(testAccount.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(testAccount);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithLead() {        
        Lead ld = [SELECT id FROM Lead LIMIT 1];
		
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(ld.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(ld);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithOpportunity() {        
        
		Opportunity testOpportunity = SELECT id FROM Opportunity LIMIT 1];

		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(testOpportunity.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(testOpportunity);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
}

 
Shravan Kumar 71Shravan Kumar 71
Thanks for your quick revert, Steven. I modified the above test class a bit and it's showing 87% coverage with below line not covered :

{
 Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No Tasks to Display'));
   } 

catch(Exception e){

Can you let me know what addition should be added to the Test Class.
Steven NsubugaSteven Nsubuga
Those line can only be covered when there are no tasks that meet the criteria being queried for.
Same thing goes for the exception,  however, given the relative simplicity of the code I see no reason to have the code within try and catch blocks.
I suggest you get rid of the catch block unless you know a way or scenario in which an exception would be thrown, and if so, you can edit the tests to be able to test that scenario.

For the no tasks scenario, see updated test class below. I have created an additional NoTasks test method for each scenario
@isTest
private class ActivitySearchControllerTest {
    
    @testSetup static void methodName() {
		
		Account testAccount = new Account (name='Test', PersonEmail = 'em@test.com', Alternate_Email__c = 'testa@test.com');
        insert testAccount;
		
		Lead ld = new Lead(Company = 'Lead Company', FirstName = 'TestF', LastName = 'TestN', Email = 'em@test.com', Alternate_Email__c = 'testb@test.com');
        insert ld;
		
		Opportunity testOpportunity = new Opportunity(
            Name = 'Test Opportunity',
			AccountId = testAccount.Id,
            CloseDate = date.today().addDays(45),         
            StageName = 'Negotiating',
            
        );
        insert testOpportunity;
		
		Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Open',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
								   Comments_Short__c = 'something'
                                   WhoId = ld.Id);
		insert newTask;						   
       
	}
	
	@isTest static  void testWithAccount() {        
        Account testAccount = [SELECT id FROM Account LIMIT 1];
        
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(testAccount.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(testAccount);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithAccountNoTasks() {        
		
		Account otherAccount = new Account (name='Test', PersonEmail = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherAccount;
		
		Lead otherLead = new Lead(Company = 'Other Company', FirstName = 'Other', LastName = 'Lead', Email = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherLead;
		
		        
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(otherAccount.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(otherAccount);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithLead() {        
        Lead ld = [SELECT id FROM Lead LIMIT 1];
		
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(ld.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(ld);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithLeadNoTasks() {        
        Lead otherLead = new Lead(Company = 'Other Company', FirstName = 'Other', LastName = 'Lead', Email = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherLead;
		
		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(otherLead.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(otherLead);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithOpportunity() {        
        
		Opportunity testOpportunity = SELECT id FROM Opportunity LIMIT 1];

		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(testOpportunity.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(testOpportunity);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
	
	@isTest static  void testWithOpportunityNoTasks() {        
        
		Account otherAccount = new Account (name='Test', PersonEmail = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherAccount;
		
		Opportunity otherOpportunity = new Opportunity(
            Name = 'Test Opportunity',
			AccountId = otherAccount.Id,
            CloseDate = date.today().addDays(45),         
            StageName = 'Negotiating',
            
        );
		
		Lead otherLead = new Lead(Company = 'Other Company', FirstName = 'Other', LastName = 'Lead', Email = 'other@test.com', Alternate_Email__c = 'testother@test.com');
        insert otherLead;

		PageReference pageRef = Page.YourPage; // Your Page
		pageRef.getParameters().put('Id', String.valueOf(otherOpportunity.Id));
		Test.setCurrentPage(pageRef); 
		
	
        Apexpages.StandardController sc = new Apexpages.StandardController(otherOpportunity);        
        ActivitySearchController ext = new ActivitySearchController(sc); 
           
    }
}

 
This was selected as the best answer