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
Hima Bindu MokaHima Bindu Moka 

Help in writing the test class for Trigger

Hi ,
I'm very new to triggers and managed to write a trigger and it works in Sandbox  and it's test cass is success but not covering code coverage show only 0. Unable to achieve code coverage, any suggestions to direct me to achieve my 100% code coverage.

I appreciate you help in advance!!

My trigger:

trigger parentCaseClose on case(before update)
{
    set<id> openCaseIDs = new set<id>();
    
    for(case caseList : [select id, ParentId, status from case where ParentId In:trigger.newMap.keyset() AND status != 'Closed'])
    {
        openCaseIDs.add(caseList.ParentId);
    }
    
    for(case newCase : trigger.new)
    {
        if(newCase.status != trigger.oldMap.get(newCase.id).status && newCase.status == 'Closed' && openCaseIDs.contains(newCase.id))
        {
            newCase.addError('The associated child cases are open');
        }
    }
}



My Test class:

@isTest

private class TestParentCaseCloseValidation {
   
  public static List<Case> createCase(string caseStatus) {
     // test account insert
    Account a = new Account();
       a.Name = 'sample account';
       insert a;
    // test contact insert
     Contact c = new Contact();
        c.FirstName = 'Test';
        c.LastName = 'contact';
        c.AccountId= a.Id;
        insert c;
        
     List<Case> cases = new List<Case>();
    // string caseStatus = 'In Progress';
     Case parent = new Case( Subject='TEST', contactID = c.id,Status=caseStatus );
        insert parent;
       
     cases.add(parent);
       // system.debug('insert parent',cases.isEmpty());
    
     Case child1 = new Case(Subject='child1',  contactID = c.id, Status=caseStatus,ParentId=parent.Id);
        insert child1;
        cases.add(child1);
    
    
     Case child2 = new Case(Subject='child2', contactID = c.id, Status=caseStatus,ParentId=parent.Id);
        insert child2;
        cases.add(child2);
        return cases;
    
    
    
 }
   
     static testMethod void testCloseParent() {
      
        List<Case> cases = createCase('In Progress');
            String parentId = null;
     //Update one of the children and see that the parent stays open
          for (Case c:cases) {
              if (c.ParentId!=null) {
                  parentId = c.ParentId;
                  c.Status = 'Closed';
                 
                }
          }
        update cases;
        //Shouldn't be closed yet
            Case parent = [select IsClosed from Case where Id=:parentId];
                System.assert(parent.IsClosed==false);
               
             for (Case c:cases) {
                    if (c.ParentId!=null && c.Status!='Closed') {
                        parentId = c.ParentId;
                        c.Status = 'Closed';
                       
                      
                    }
                }update cases;
        
       
    
       
        test.startTest();
                          
    try
   
        {
            update parent;
 
        }

        catch(System.DMLException e)

        {

            System.assert(e.getMessage().contains('There are still Child Cases Open '));

        }
     test.stopTest();
    }
}
Best Answer chosen by Hima Bindu Moka
v varaprasadv varaprasad
Hi Hima Bindu,

Please check once following code : 
 
============== Trigger code ================
trigger parentCaseClose on case(before update)
{
    set<id> parentcaseIds = new set<id>();
    
    for(case cs : trigger.new){
        if(cs.status == 'Closed'){
            parentcaseIds.add(cs.id);
        }
        
    }
    
    list<case> childCases = [select id, ParentId, status from case where ParentId In:parentcaseIds AND status != 'Closed'];
    system.debug('==childCases=='+childCases.size());
        if(childCases.size()>0){
            for(case newCase : trigger.new){
                newCase.addError('The associated child cases are open');
            }    
        }
    
}

=================Test class ===================
@isTest
public class parentCaseClose_Test {
    
    @testsetup
    public static void testData(){
        test.startTest();
        
        Account a = new Account();
        a.Name = 'sample account';
        insert a;
        
        Contact c = new Contact();
        c.FirstName = 'Test';
        c.LastName = 'contact';
        c.AccountId = a.id;
        insert c;
        
        case parentcase = new case();
        parentcase.status = 'open';
        parentcase.ContactId = c.id;
        insert parentcase;
        
        case childcase = new case();
        childcase.ParentId = parentcase.id;
        childcase.Status = 'open';
        childcase.ContactId = c.id;
        insert childcase;
        
        test.stopTest();
        
    }
    
    
    static testMethod void testCloseParent() {        
        list<case> lstCases = [select id,parentid from case order by createddate];
        list<case> updlstCases  = new list<case>();
        for(case cs : lstCases){
            cs.status = 'closed';
            updlstCases.add(cs);
        }
        
        try{
            update updlstCases;
        } catch(Exception e){            
            Boolean expectedExceptionThrown =  e.getMessage().contains('The associated child cases are open') ? true : false;
            System.AssertEquals(expectedExceptionThrown, true);
        } 
        
    }
}
====================================================

Hope this helps you!

Thanks
Varaprasad
For Support: varaprasad4sfdc@gmail.com


 

All Answers

v varaprasadv varaprasad
Hi HimaBindu,

Please let me know your requirement. I think your trigger is not working properly.
So based on that I will help you.

Sample test class code : 
 
@isTest
public class parentCaseClose_Test {
    
    @testsetup
    public static void testData(){
        test.startTest();
        set<id> parentids = new set<id>();
        case parentcase = new case();
        parentcase.status = 'open';
        insert parentcase;
        parentids.add(parentcase.id);
        
        case childcase = new case();
        childcase.ParentId = parentcase.id;
        childcase.Status = 'open';
        insert childcase;
        
        test.stopTest();
        
    }
    static testMethod void testCloseParent() {
        list<case> lstCases = [select id,parentid from case order by createddate desc limit 1];
        list<case> updlstCases  = new list<case>();
        for(case cs : lstCases){
              cs.status = 'closed';
            updlstCases.add(cs);
        }
        
        update updlstCases;
        
    }
}

 
Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com
 
v varaprasadv varaprasad
Hi Hima Bindu,

Please check once following code : 
 
============== Trigger code ================
trigger parentCaseClose on case(before update)
{
    set<id> parentcaseIds = new set<id>();
    
    for(case cs : trigger.new){
        if(cs.status == 'Closed'){
            parentcaseIds.add(cs.id);
        }
        
    }
    
    list<case> childCases = [select id, ParentId, status from case where ParentId In:parentcaseIds AND status != 'Closed'];
    system.debug('==childCases=='+childCases.size());
        if(childCases.size()>0){
            for(case newCase : trigger.new){
                newCase.addError('The associated child cases are open');
            }    
        }
    
}

=================Test class ===================
@isTest
public class parentCaseClose_Test {
    
    @testsetup
    public static void testData(){
        test.startTest();
        
        Account a = new Account();
        a.Name = 'sample account';
        insert a;
        
        Contact c = new Contact();
        c.FirstName = 'Test';
        c.LastName = 'contact';
        c.AccountId = a.id;
        insert c;
        
        case parentcase = new case();
        parentcase.status = 'open';
        parentcase.ContactId = c.id;
        insert parentcase;
        
        case childcase = new case();
        childcase.ParentId = parentcase.id;
        childcase.Status = 'open';
        childcase.ContactId = c.id;
        insert childcase;
        
        test.stopTest();
        
    }
    
    
    static testMethod void testCloseParent() {        
        list<case> lstCases = [select id,parentid from case order by createddate];
        list<case> updlstCases  = new list<case>();
        for(case cs : lstCases){
            cs.status = 'closed';
            updlstCases.add(cs);
        }
        
        try{
            update updlstCases;
        } catch(Exception e){            
            Boolean expectedExceptionThrown =  e.getMessage().contains('The associated child cases are open') ? true : false;
            System.AssertEquals(expectedExceptionThrown, true);
        } 
        
    }
}
====================================================

Hope this helps you!

Thanks
Varaprasad
For Support: varaprasad4sfdc@gmail.com


 
This was selected as the best answer
Hima Bindu MokaHima Bindu Moka
Hi @Varaprasad,
 Thanks again! for your help but I noticed one more challege while deploying these two class (trigger with 100% code coverage and testclass 0% code coverage ) which shows error that deploy is failed saying Each trigger must have at least 1% code coverage.
Please Note: there are no Hardcoded reference Id's in the Trigger and Test Class.

I appreciate your help!