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
sumit dsumit d 

Case Milestone creation in test class

Hi All, 
         I Have created a  test class for  the class below:-

public class MilestoneUtils {
    
    // Method Description : This method is use to Complete Case MileStone And Update Case fields when Email to Customer and Others
     
    public static void completeMilestone(Set<Id> caseIds,DateTime complDate){
        Set<Id> lstOfcaseId =caseIds;
        Map<Id,CaseMilestone> mapofCaseIdToMilestone = new Map<Id,CaseMilestone>();
        List<Case> casetoUpdate = new List<Case>();
        List<CaseMilestone> cmsToUpdate = [select Id,CaseId, completionDate
                                           from CaseMilestone cm
                                           where caseId in :caseIds and IsCompleted = false
                                           and completionDate = null AND MilestoneType.Name !='Full Resolution' limit 1];
        if (cmsToUpdate.isEmpty() == false){
            for (CaseMilestone cm : cmsToUpdate){
                cm.completionDate = complDate;
            }
            try{
                Database.SaveResult[] srList =Database.update(cmsToUpdate, True);
                CommonUtility.saveResults(srList);
            }catch(Exception e){
                ExceptionLogUtil.logException('MilestoneUtils','completeMilestone',e.getMessage(),e.getStackTraceString());

            }
            CaseMilestone mil= [SELECT caseId,MilestoneType.Name,ActualElapsedTimeInMins from CaseMilestone Where id=:cmsToUpdate order by createdDate DESC];
            mapofCaseIdToMilestone.put(mil.caseId,mil);
        }
        for(Case c : [Select status,Time_To_First_response__c,Last_Time_Waiting_Status__c,Is_Next_Reply__c,
                      count_of_outbound_emails__c,Last_Outbound_Email__c from Case where id In : caseIds]){
                          //c.status ='Waiting on Customer';
                          c.Last_Time_Waiting_Status__c = system.now();
                          if(mapofCaseIdToMilestone != null && mapofCaseIdToMilestone.containsKey(c.id)){
                              if(mapofCaseIdToMilestone.get(c.id).MilestoneType.Name == 'Next Reply'){
                                  c.Time_To_Next_Reply_Minutes__c = mapofCaseIdToMilestone.get(c.id).ActualElapsedTimeInMins;
                              }
                              if(mapofCaseIdToMilestone.get(c.id).MilestoneType.Name == 'First Reply'){
                                  c.Time_To_First_response__c = mapofCaseIdToMilestone.get(c.id).ActualElapsedTimeInMins;  
                              }
                          }
                          if(c.count_of_outbound_emails__c == NULL){
                              c.count_of_outbound_emails__c = 0;
                          }
                          c.count_of_outbound_emails__c++;
                          c.Last_Outbound_Email__c = System.now();
                          c.Is_Next_Reply__c = false;
                          casetoUpdate.add(c);
                          
                      } 
        if(casetoUpdate.size()>0){
            try{
                Database.SaveResult[] srList = Database.update(casetoUpdate, true);
                CommonUtility.saveResults(srList);
            }catch(Exception e){
                ExceptionLogUtil.logException('MilestoneUtils','completeMilestone',e.getMessage(),e.getStackTraceString()); 
            }
        }
    }
    
    
    public static void closedCaseMileStone(List<Case> list_cases, Map<Id,Case> applicableCase){
        Map<Id,Integer> maofCaseIdToEmail = new Map<Id,Integer>();
        Map<Id,CaseMilestone> mapofCaseIdToMilestone = new Map<Id,CaseMilestone>();
        for(AggregateResult aggr : [SELECT ParentId, COUNT_DISTINCT(CreatedById)usercount FROM EmailMessage 
                                    WHERE ParentId IN :applicableCase.keySet()
                                    AND Status != '5' AND Incoming = false 
                                    group by ParentId ])
        {
            maofCaseIdToEmail.put(String.valueOf(aggr.get('ParentId')), Integer.valueOf(aggr.get('usercount')));        
        }
        List<CaseMilestone> milestonesToUpdate = new List<CaseMilestone>();
        List<CaseMilestone> cms = [select Id,caseId,completionDate,ActualElapsedTimeInMins
                                   from CaseMilestone 
                                   where caseId in :applicableCase.keySet() and IsCompleted = false
                                   and completionDate = null];
        if(cms.size()>0){
            for(CaseMilestone cm : cms){
                if(applicableCase.containsKey(cm.CaseId)){
                    if(applicableCase.get(cm.CaseId).autoSolved__c){
                        cm.completionDate = applicableCase.get(cm.CaseId).Last_Outbound_Email__c;
                    }
                    else
                        cm.completionDate = applicableCase.get(cm.CaseId).Last_Set_Solved__c; 
                }
                
                mapofCaseIdToMilestone.put(cm.caseId,cm);
                milestonesToUpdate.add(cm);
            }
            if(milestonesToUpdate.size()>0){
                try{
                    Database.SaveResult[] srList = Database.update(milestonesToUpdate, false);
                    CommonUtility.saveResults(srList);
                }catch(Exception e){
                    ExceptionLogUtil.logException('MilestoneUtils','closedCaseMileStone',e.getMessage(),e.getStackTraceString()); 
                }
                CaseMilestone mil= [SELECT caseId,ActualElapsedTimeInMins from CaseMilestone Where caseId IN : applicableCase.keySet()  
                                    AND MilestoneType.Name ='Full Resolution' limit 1];
                mapofCaseIdToMilestone.put(mil.caseId,mil);

            }
        }
        for(Case c : list_cases){
            if(maofCaseIdToEmail != null && maofCaseIdToEmail.containsKey(c.id)){
                c.count_of_unique_CSAs__c = maofCaseIdToEmail.get(c.id);
            }
            if(mapofCaseIdToMilestone != NULL && mapofCaseIdToMilestone.containsKey(c.id)){
                // removing this as when we case opened from solved then this is updating to last time solved.
                //if(c.Time_To_First_Solved__c == NULL){
                //    c.Time_To_First_Solved__c = mapofCaseIdToMilestone.get(c.id).ActualElapsedTimeInMins;
                //}
                if(c.Time_To_First_Response__c == NULL){
                    c.Time_To_First_Response__c = mapofCaseIdToMilestone.get(c.id).ActualElapsedTimeInMins;
                }
                c.Time_To_Resolution__c = mapofCaseIdToMilestone.get(c.id).ActualElapsedTimeInMins;
            }
        }
    }
    } 
My test class is given below:-
@isTest 
private class Test_MilestoneUtils {
    
    @isTest
    public static void completeMilestone_Test(){
        //Set<Id> caseids = new Set<Id>();
        List<Case> cases = new List<Case>{};
            Account acc = new Account(Name = 'Entitlement Account DO NOT DELETE');
        insert acc;
        Entitlement en = TestFactory.createEntitlement(acc, 'Enterprise');
        insert en;
        HB_User__c h = TestFactory.createAirtableUser(100,'Enterprise');
        insert h;
        Case c = TestFactory.createCase(h);
        c.Priority = 'Business Critical';
        c.EntitlementId = en.id;
        c.Company_Number_of_employees__c = 1100;
        cases.add(c);
         
        if (cases.isEmpty()==false){
            insert cases;
             Set<Id> caseIds = new Set<Id>();
            Map<id,Case> mapCases= new Map<id,Case>();
            for (Case cl : cases){
                caseIds.add(cl.Id);
                mapCases.put(cl.id,cl);
             }
             milestoneUtils.completeMilestone(caseIds,System.now());
             milestoneUtils.closedCaseMileStone(cases,mapCases);
        }
    }
 }
I am getting less code coverage. Bold lines in my class is not covering. Can anyone help me to cover the lines.
Thanks
SwethaSwetha (Salesforce Developers) 
HI Sumit,
Since this code is huge and requires an understanding of your implementation, it might not be possible to provide exact edit suggestions. However, the below articles give a good insight into how coverage can be improved
 
https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines 
 
Examples of Milestone completion test classes:
https://salesforce.stackexchange.com/questions/150226/milestone-completion-test-class-not-getting-100-code-coverage
 
https://salesforce.stackexchange.com/questions/141607/57-code-coverage-on-milestone-complete
 
https://salesforce.stackexchange.com/questions/275562/i-am-writing-a-test-class-on-case-object-with-entitlement-and-im-receiving-an
 
Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you