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
Antoine LeleuAntoine Leleu 

Help Test class for trigger on Case & CaseMilestone

Hello all,

I need help to have 100% code coverage on trigger. 
Only 57% are covered by the test and the 3 last lines are not.
This is my trigger (to prevent the closure of case if the completion of case milsetones are not filled)

trigger MilestoneCompletionDateRequiredToClose on Case (before update) {
   
     for (Case c : trigger.new) {
        if(c.Status == 'Closed'){
             List<CaseMilestone> CaseMls = [select Id, completionDate from CaseMilestone
                       where caseId = :c.Id ];
            if(CaseMls.isEmpty() == false){          
                for (CaseMilestone cm : CaseMls){
                    if(cm.CompletionDate == null)
                    c.addError('The completion Date of Case Milestone(s) must be filled to close the case');   
                }  
            }
        }
     }
}

and this my test :

"@isTest
private class MilestoneCompletionDateRequiredTest {

    static testMethod void CloseCaseTest() {
        // TO DO: implement unit test
   
  Account acc = new account(name = 'TestCoverage', Zone__c = 'EMEA');
        insert acc;
    Contact con = new contact(accountId = acc.id, lastname='Coverage', firstname='Test');
        insert con;
        Entitlement ent = new entitlement(name = 'CoverageEntitlement', AccountId = acc.Id);
        insert ent;
  Case cseA = new case(accountId = acc.id, contactId = con.id, subject = 'TestCoverage1', EntitlementId = ent.Id);
        insert cseA;
       
        List<CaseMilestone> CaseMls = [select Id, completionDate from CaseMilestone
                            where caseId = :cseA.Id ];
        
      cseA.status = 'Closed';
        try{
   update cseA;
  }catch(Exception e){
         if(CaseMls.isEmpty() == false){          
             for (CaseMilestone cm : CaseMls){
              if(cm.completionDate == null){
      system.assertEquals(e.getMessage(), 'The completion Date of Case Milestone(s) must be filled to close the case');
     }
             }
         }
       }  
   }  
}"

thanks for your help
Ashish_SFDCAshish_SFDC
Hi , 


You have to write some dummy methods that meet the If condition in the loop and then assert to check if returns the expected values. 


Regards,
Ashish