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
shakila Gshakila G 

Apex class Code Coverage error ?

Kindly let me know, how to write a test class for this Apex class. I wrote a test class but it's not covering code coverage

public class AggregateTasklist{
public List<AggregateResult> Result {get;set;} 
List<Account> ListAct= New List<Account>();
 
public List<AddWrapperField> wraplist{get;set;}
 
    public AggregateTasklist(ApexPages.StandardController controller) {       
        
    }
    
    public void GetRecords(){
    
        String userid=UserInfo.getUserId();
        
        ListAct=[select ID,ownerId from Account where ownerId =:userid];
        
        If(ListAct.size()>0) {
        For(Account act:ListAct) {   
        wraplist=new List<AddWrapperField>();        
        Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task where  ownerId =:userid and Time_New__c!=Null 
        group By Task.Account.Name Having Max(Time_New__c)<LAST_N_DAYS:110]; 
          }
       }      
       for(AggregateResult res:Result){          
       wraplist.add(new AddWrapperField(Res));    
       }   
    }

    public class AddWrapperField{
       public Date LastDueDate{get;set;}
       public String Name {get;set;}
       
       AddWrapperField(AggregateResult res){
         this.LastDueDate=(Date)res.get('LastDueDate');
         this.Name =(String)res.get('Name');
         
       }
     }
     
    }


My Test Class:

@isTest(SeeAllData=false) class AggregateResultTest {
    @isTest static void test() {
    
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
            
             
            Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
           insert a; 
           
           Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
    
     System.runAs(u) 
        { 
            Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             Insert testTTask;
             
             
        Test.startTest();
        testTTask= new task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
        ownerid=con.ownerid);
        Database.SaveResult result = Database.insert(testTTask, false);
           Test.stopTest();
           }
        
    
    
    
     List<Account> listact=New List<Account>{[select OwnerID from Account Where ownerID=:u.ID ]};
    
        AggregateResult[] results = [SELECT Max(Time_New__c), WhatId  FROM Task GROUP BY WhatId ];
        
        }
      
    }
Best Answer chosen by shakila G
Amit Chaudhary 8Amit Chaudhary 8
Update your code like below
@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
    static void test() 
    {
    
    
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
        insert a; 

        Contact con = new COntact();
        con.email='test@fmail.co';
        con.ACCOUNTID=a.ID;
        con.lastname='test' ;
        insert con;

        Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id,
        whatid=a.ID);
		
		testTTask.Time_New__c = System.now();// add value according to data type

        Insert testTTask;
             
             
        Test.startTest();
		
			Apexpages.Standardcontroller SC= new Apexpages.StandardController(a);                  
            AggregateTasklist obj = new AggregateTasklist(sc);
            obj.GetRecords();
            obj.Getwraplist();
            
			List<AggregateResult>  Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task ]; 
			obj.wraplist = new new List<AggregateTasklist.AddWrapperField>();        
			for(AggregateResult res:Result){          
				obj.wraplist.add(new AggregateTasklist.AddWrapperField(Res));    
			}
			
        Test.stopTest();
        
    }
}

Let us know if this will help you
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Try below test class
@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
	static void test() 
	{
	
		Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
		insert a; 

		Contact con = new COntact();
		con.email='test@fmail.co';
		con.ACCOUNTID=a.ID;
		con.lastname='test' ;
		insert con;

		Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id );
		Insert testTTask;
             
             
		Test.startTest();
			ApexPages.StandardController sc = new ApexPages.StandardController(a);
			AggregateTasklist obj = new AggregateTasklist(sc);
			obj.GetRecords();
			
        Test.stopTest();
		
    }
}

Let us know if this will help you
 
shakila Gshakila G
HI Amit,

Thanks for the reply,

Still am unable complete code coverage., Kindly let me know what i missed

User-added image
My Apex class Code Coverage 70 %

public class AggregateTasklist{
public List<AggregateResult> Result {get;set;} 
List<Account> ListAct= New List<Account>();
 
public List<AddWrapperField> wraplist{get;set;}

 public list<AddWrapperField> getwraplist(){
        return wraplist;
    }

 
    public AggregateTasklist(ApexPages.StandardController controller) {       
        
    }
    
    public void GetRecords(){
    
        String userid=UserInfo.getUserId();
        
        ListAct=[select ID,ownerId from Account where ownerId =:userid];
        
        If(ListAct.size()>0) {
        For(Account act:ListAct) {   
        wraplist=new List<AddWrapperField>();        
        Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task where  ownerId =:userid and Time_New__c!=Null 
        group By Task.Account.Name Having Max(Time_New__c)<LAST_N_DAYS:110]; 
          }
       }      
       for(AggregateResult res:Result){          
       wraplist.add(new AddWrapperField(Res));    
       }   
    }

    public class AddWrapperField{
       public Date LastDueDate{get;set;}
       public String Name {get;set;}
       
       AddWrapperField(AggregateResult res){
         this.LastDueDate=(Date)res.get('LastDueDate');
         this.Name =(String)res.get('Name');
         
       }
     }
     
    }

My Test Class

@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
    static void test() 
    {
    
     Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
    
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
        insert a; 

        Contact con = new COntact();
        con.email='test@fmail.co';
        con.ACCOUNTID=a.ID;
        con.lastname='test' ;
        insert con;

        Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id,
        whatid=a.ID,OwnerID=U.ID);
        Insert testTTask;
       
        
        
                     
             
             
        Test.startTest();
         ApexPages.CurrentPage().getParameters().put('id',U.Id);
        Apexpages.Standardcontroller SC= new Apexpages.StandardController(U);                  
             AggregateTasklist obj = new AggregateTasklist(sc);
             obj.GetRecords();
             obj.Getwraplist();
            
           
            
        Test.stopTest();
        
    }
}



 
Amit Chaudhary 8Amit Chaudhary 8
Please set value for below field

testTTask.Time_New__c = System.now();// add value according to data type

Try below code
@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
    static void test() 
    {
    
    
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
        insert a; 

        Contact con = new COntact();
        con.email='test@fmail.co';
        con.ACCOUNTID=a.ID;
        con.lastname='test' ;
        insert con;

        Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id,
        whatid=a.ID);
		
		testTTask.Time_New__c = System.now();// add value according to data type

        Insert testTTask;
             
             
        Test.startTest();
		
			Apexpages.Standardcontroller SC= new Apexpages.StandardController(a);                  
            AggregateTasklist obj = new AggregateTasklist(sc);
            obj.GetRecords();
            obj.Getwraplist();
            
        Test.stopTest();
        
    }
}

 
shakila Gshakila G
Its an formula field . this Field is not writeable in test class
Amit Chaudhary 8Amit Chaudhary 8
plz set the data according to formula field so that some value will populate in formula. Than only record will come in query
shakila Gshakila G
After passing the value for the field also am getting same code coverage
Amit Chaudhary 8Amit Chaudhary 8
can you please post your formula field and let me know what code changes you did ?
shakila Gshakila G
This is my Apex class

public with sharing class AggregateTasklist{
public List<AggregateResult> Result {get;set;} 
List<Account> ListAct= New List<Account>();
 
public List<AddWrapperField> wraplist{get;set;}

 public list<AddWrapperField> getwraplist(){
        return wraplist;
    }

 
    public AggregateTasklist(ApexPages.StandardController controller) {       
        
    }
    
    public void GetRecords(){
    
        String userid=UserInfo.getUserId();
        
        ListAct=[select ID,ownerId from Account where ownerId =:userid];
        
        If(ListAct.size()>0) {
        For(Account act:ListAct) {   
        wraplist=new List<AddWrapperField>();        
        Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task where  ownerId =:userid and Time_New__c!=Null 
        group By Task.Account.Name Having Max(Time_New__c)<LAST_N_DAYS:110]; 
          }
       }      
       for(AggregateResult res:Result){          
       wraplist.add(new AddWrapperField(Res));    
       }   
    }
    
    
    

    public class AddWrapperField{
       public Date LastDueDate{get;set;}
       public String Name {get;set;}
       
       AddWrapperField(AggregateResult res){
         this.LastDueDate=(Date)res.get('LastDueDate');
         this.Name =(String)res.get('Name');
         
       }
     }
     
    }


Test Class:
@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
    static void test() 
    {
     List<AggregateResult> Result=New  List<AggregateResult>();
    
     Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
    
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
        insert a; 

        Contact con = new COntact();
        con.email='test@fmail.co';
        con.ACCOUNTID=a.ID;
        con.lastname='test' ;
        insert con;

        Task testTTask= new Task(Subject = 'EventTest',
        ActivityDate=Date.newInstance(2018, 03, 23), // Formula field of(Time_New__c​)
          Description = 'Description',
          WhoId= con.Id,
        whatid=a.ID,OwnerID=U.ID);
        Insert testTTask;
        
       Test.StartTest(); 
        list<AddWrapperField> wraplist= new  list<AddWrapperField>();  
               
        Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task where  ownerId =:U.ID and Time_New__c!=Null 
        group By Task.Account.Name Having Max(Time_New__c)<LAST_N_DAYS:110]; 
        
        for(AggregateResult res:Result){ 
                 
               wraplist.add(new AddWrapperField(Res));    
           }   
    
        ApexPages.CurrentPage().getParameters().put('id',U.Id);
        Apexpages.Standardcontroller SC= new Apexpages.StandardController(testTTask);                  
             AggregateTasklist obj = new AggregateTasklist(sc);
              obj.GetRecords();
             obj.Getwraplist();                      
             
                      
             Test.StopTest();  
          
         
        
    }
    
    public class AddWrapperField{
       public Date LastDueDate{get;set;}
       public String Name {get;set;}
       
       AddWrapperField(AggregateResult res){
         this.LastDueDate=(Date)res.get('LastDueDate');
         this.Name =(String)res.get('Name');
         
       }
     }

    
    
}

 
Amit Chaudhary 8Amit Chaudhary 8
Please share the screen shot of of your formula.
 
Amit Chaudhary 8Amit Chaudhary 8
NOTE:- You dnt need to create a new user and add that user as owner. You apex class is using runing user and checking the same in qury

You can try below code
@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
    static void test() 
    {
    
    
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
        insert a; 

        Contact con = new COntact();
        con.email='test@fmail.co';
        con.ACCOUNTID=a.ID;
        con.lastname='test' ;
        insert con;

        Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id,
        whatid=a.ID);
		
		testTTask.Time_New__c = System.now();// add value according to data type

        Insert testTTask;
             
             
        Test.startTest();
		
			Apexpages.Standardcontroller SC= new Apexpages.StandardController(a);                  
            AggregateTasklist obj = new AggregateTasklist(sc);
            obj.GetRecords();
            obj.Getwraplist();
            
			List<AggregateResult>  Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task ]; 
			obj.wraplist = new new List<AggregateTasklist.AddWrapperField>();        
			for(AggregateResult res:Result){          
				obj.wraplist.add(new AddWrapperField(Res));    
			}
			
        Test.stopTest();
        
    }
}

 
shakila Gshakila G
Am trying to aggregate a Max(Activitydate) field in Apex but, it's not allowing to aggregate this field in the apex, So I created custom formula field to replicate of Activity date.
Time_New__c= Activitydate
Amit Chaudhary 8Amit Chaudhary 8
then pass Activitydate and try above code which i just posted. And let us know the result
shakila Gshakila G
Compile Error: Invalid type: AddWrapperField at line 36 column 34
Amit Chaudhary 8Amit Chaudhary 8
Update your code like below
@isTest(SeeAllData=false) 

class AggregateResultTest {
    @isTest 
    static void test() 
    {
    
    
        Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE);
        insert a; 

        Contact con = new COntact();
        con.email='test@fmail.co';
        con.ACCOUNTID=a.ID;
        con.lastname='test' ;
        insert con;

        Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id,
        whatid=a.ID);
		
		testTTask.Time_New__c = System.now();// add value according to data type

        Insert testTTask;
             
             
        Test.startTest();
		
			Apexpages.Standardcontroller SC= new Apexpages.StandardController(a);                  
            AggregateTasklist obj = new AggregateTasklist(sc);
            obj.GetRecords();
            obj.Getwraplist();
            
			List<AggregateResult>  Result=[select Max(Time_New__c) LastDueDate, Task.Account.Name Name from Task ]; 
			obj.wraplist = new new List<AggregateTasklist.AddWrapperField>();        
			for(AggregateResult res:Result){          
				obj.wraplist.add(new AggregateTasklist.AddWrapperField(Res));    
			}
			
        Test.stopTest();
        
    }
}

Let us know if this will help you
 
This was selected as the best answer
shakila Gshakila G
Same  compile error
shakila Gshakila G
Error: Compile Error: Method is not visible: void AggregateTasklist.AddWrapperField.<init>(AggregateResult) at line 36 column 34
shakila Gshakila G
Hi Amit,

While try to validate the code am getting following error.
AggregateTasklistApex Class2516By Task.Account.Name Having Max(Time_New__c)<LAST_N_DAYS:110 ^ ERROR at Row:2:Column:47 value of filter criterion for expression MAX(Time_New__c) must be of type string and should be enclosed in quotes

 
Amit Chaudhary 8Amit Chaudhary 8
Please fix your apex class this is your apex class issue. I hope you created Time_New__c data type as String. Make it number