+ Start a Discussion
devloper sfdcdevloper sfdc 

Write Test class of trigger

Please help me for Writing Test Class on Trigger
trigger ParentToCaseClosure on Case (after update,before update) {
  
    
   
    if(trigger.isAfter && trigger.isUpdate) {
     
      

        List<Case> childrenToUpdate = new List<Case>();
        Set<Id> parentIds = new Set<Id>();
        for(Case p:trigger.new) {
        system.debug('******CASE ID ::::'+ p.id);
            case old=trigger.oldMap.get(p.id);
            if(p.IsClosed == TRUE ) {
                    
            
            
                
                parentIds.add(p.Id);
              
                 
               
        }
       
        System.debug('------------- Parent Ids -------- ' + parentIds);
        if(parentIds.size() > 0) {
            for(Case ch : [SELECT Id, Status, Parent.Status FROM Case WHERE Parent.Id IN :parentIds]) {
                 if(ch.Status=='Closed Successful')
                 { system.debug('--no update');}
                ch.Status = ch.Parent.Status;
                childrenToUpdate.add(ch);
            }
           
            System.debug('---------------- Child Case(s) Received : ' + childrenToUpdate.size());           
            try{
                System.debug('---------Going to update the children');
                update childrenToUpdate;
                System.debug('---------Children updated successfully');
            }
            catch(Exception e) {
                System.debug('--------------Exception in updating all the Parents');
            }
        }
        } 
}
    }
Please Write Test Class for Trigger.
Best Answer chosen by devloper sfdc
TBouscalTBouscal
Here's one you can add to. 
 
@isTest(SeeAllData=true)

public class ParentToCaseClosure_Test {
    
    @istest static void testSuccess(){
        Account testAccount = createAccount(); 
        Contact testContact = createContact(testAccount); 
        Case testChild = createCase(testAccount, testContact); 
        Case testParent = createChild(testAccount, testContact, testChild.id); 
        
        testChild.status = 'Closed';
        update testChild; 
        
        System.assertEquals('Closed', testChild.Status); 
        
    }
    
    @istest static void testFail(){
        
        
    }
    
    @istest static void testBulk(){
        
        
    }
    
    // helpers for creating test objects    
    public static Account createAccount(){
        Account theAccount = new Account(
            name='My Test Account', 
            phone='8005551212'); 
        
        insert theAccount; 
        return theAccount; 
    }  
    
    public static Contact createContact(Account acc){
        Contact theContact = new Contact(
            accountid=acc.id, 
            firstname='John', 
            lastname='Doe', 
            phone='8005551212'); 
        
        insert theContact; 
        return theContact; 
    }
    
    public static Case createCase(Account acc, Contact con){
        Case theCase = new Case(
            Subject='Test',
            AccountId=acc.Id,
            ContactId=con.Id, 
            Status='New');   
        
        insert theCase; 
        return theCase; 
    }
    
    public static Case createChild(Account acc, Contact con, id parentid){
        Case theChild = new Case(
            Subject='Test',
            AccountId=acc.id,
            ContactId=con.id, 
            Status='New',
            parentid = parentid); 
        
        insert theChild; 
        return theChild; 
    }
    
}

 

All Answers

TBouscalTBouscal
Hi there, what have you tried so far?

Here's an intro to writing a test class; 
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

and some examples; 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

Looks like you'll need to create some parent and child test records and a record without a parent or child to get a complete test.
 
TBouscalTBouscal
Here's one you can add to. 
 
@isTest(SeeAllData=true)

public class ParentToCaseClosure_Test {
    
    @istest static void testSuccess(){
        Account testAccount = createAccount(); 
        Contact testContact = createContact(testAccount); 
        Case testChild = createCase(testAccount, testContact); 
        Case testParent = createChild(testAccount, testContact, testChild.id); 
        
        testChild.status = 'Closed';
        update testChild; 
        
        System.assertEquals('Closed', testChild.Status); 
        
    }
    
    @istest static void testFail(){
        
        
    }
    
    @istest static void testBulk(){
        
        
    }
    
    // helpers for creating test objects    
    public static Account createAccount(){
        Account theAccount = new Account(
            name='My Test Account', 
            phone='8005551212'); 
        
        insert theAccount; 
        return theAccount; 
    }  
    
    public static Contact createContact(Account acc){
        Contact theContact = new Contact(
            accountid=acc.id, 
            firstname='John', 
            lastname='Doe', 
            phone='8005551212'); 
        
        insert theContact; 
        return theContact; 
    }
    
    public static Case createCase(Account acc, Contact con){
        Case theCase = new Case(
            Subject='Test',
            AccountId=acc.Id,
            ContactId=con.Id, 
            Status='New');   
        
        insert theCase; 
        return theCase; 
    }
    
    public static Case createChild(Account acc, Contact con, id parentid){
        Case theChild = new Case(
            Subject='Test',
            AccountId=acc.id,
            ContactId=con.id, 
            Status='New',
            parentid = parentid); 
        
        insert theChild; 
        return theChild; 
    }
    
}

 
This was selected as the best answer
devloper sfdcdevloper sfdc
Hello TBouscal

We Can't getting   100% code coverage after using your Test class we got 46% code coverage  I need atleat 85%code coverage My   Org. Over all code coverage is 25%. we are facing code coverage problem when i deploy trigger. please help.
 
TBouscalTBouscal
Are you getting 46% org wide or for this specific trigger?

My incomplete test code provides 93% coverage for the trigger as provided with only the exception line being ignored.  It is incomplete becase you will want to test for failures to insure they are trapped and bulk loading of 200+ records.  Your bulk test will reveal the SOQL inside a loop which will cause a bulk test to throw an exception.

There's is a mix-up in my test, lines 11 and 12 should be the parent case, not the child.  Then the assertion shows that your code isn't updating the children. 

As I read through this, here's what I see; 

If this case WAS closed prior to this trigger firing (oldmap), add the parent id to a set (parentIds)

If the parentids set has members then 
  FOR EACH case in a new list
     IF the child case is closed
         set the child status to the status of the parent
         update the child

What is the desired end result?  When a parent case is closed then close all the child cases?









 
devloper sfdcdevloper sfdc
When Parent Case closed all corresponding child should be closed .
devloper sfdcdevloper sfdc
i am getting 46% for Specific Trigger.
TBouscalTBouscal
Is there anything missing from the code posted here?  Not understanding how you're getting a lower coverage % than I am.
devloper sfdcdevloper sfdc
not missing
TBouscalTBouscal
Could you point out which lines are not covered?  Running the test in the dev console, then opening the trigger from the Overall Code Coverage pane on the Tests tab will show covered lines in blue and uncovered lines in red/pink.  Below is what I get with your code and my test.

Code Coverage

NOTE: because "Closed Successful" isn't a value in my system I changed it to "Closed" in mine.  You need to edit the test to match your values to get to 93%.  
You SHOULD also add tests for failures and bulk inserts (> 200 records).
Shubham Joge 9Shubham Joge 9
Please help me for Writing Test Class on Trigger


public class case_Parentchild_helper {
    
    
    public Static Map<Id,case> getCaseRec(Set<Id> setofcaseParentId){        
        Map<Id,case> mapofCase = new Map<Id,Case>([Select Id, parentId from Case where parentId in : setofcaseParentId]);
        return mapofCase;
    }
    
    public static void beforeInsert(list<Case> lstCase){        
        set<Id> parentCaseId = new Set<Id>();
        
        for(Case childCaseRec :lstCase){
            
            if(childCaseRec.parentId !=null){ 
                //means child is being inserted this is being executed in for loop
                parentCaseId.add(childCaseRec.parentId);
            }
        }
        //query outside of for
        Map<Id, Case> existingChildCaseMap = new Map<Id, Case>();
        
        //this for is outside of outer for
      /*  for(case childCaseRec : [Select Id, parentId from Case where parentId in : parentCaseId]){
            existingChildCaseMap.put(childCaseRec.parentId, childCaseRec);
        }*/
        
        existingChildCaseMap = case_Parentchild_helper.getCaseRec(parentCaseId);
        
        for(case caseRec : lstCase){
            
            if(!existingChildCaseMap.isEmpty() && existingChildCaseMap.containsKey(caseRec.parentId)){
                //check not required but just to debug and observe
                
                if(existingChildCaseMap.get(caseRec.parentId) !=null){
                    caseRec.addError('can\'t add second child on parent');
                    
                }
                
            }
        }
    }