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
coolkrishcoolkrish 

catch block code coverate

Hi,

I am trying to get code coverage for catch block.

 try {
                update empMap.values();
              } catch(Exception e) {
                Trigger.new.get(0).addError('Unable to update address details on Account');
            }     

this is my test calss:

@isTest
public class RRAddress_Copy_To_Employee_Test {    
    public static testMethod void runTestCases() { 
        try  {
        //Insert RREmployee__c 
        RREmployee__c emp = new RREmployee__c();
        emp.First_Name__c='Test';
          emp.Last_Name__c='Emp';
        emp.Name = 'Test emp';
        emp.Franchise__c = 'test franchise';
        emp.Territory_ID__c ='100';
        insert emp;
        System.assertEquals ('Test emp', emp.Name);
        
        // insert Address
        RRAddress__c addr1 = new RRAddress__c();
        addr1.Employee__c = emp.Id;
        addr1.Type__c = 'Sampling';
        addr1.Name ='street line1';
        addr1.Address_Line_2__c='Street Line2';
        addr1.Address_Line_3__c='Street Line3';
        addr1.City__c = 'Sunnyvale';
        addr1.State__c = 'CA';
        addr1.Zip__c ='99999';
        addr1.Country__c ='USA';
        
        insert addr1;
        
        System.assertEquals ('street line1', addr1.Name);
        
        // update Address        
        addr1.Type__c = 'Sampling';
        addr1.Name ='street line11';
        addr1.Address_Line_2__c='Street Line22';
        addr1.Address_Line_3__c='Street Line33';
        addr1.City__c = 'Mountain View';
        addr1.State__c = 'TN';
        addr1.Zip__c = '99999';
        addr1.Country__c ='CAN';
        
        update addr1;
        System.assertEquals ('street line11', addr1.Name);
        }catch(DmlException e){
            System.assert(e.getMessage().contains('Unable to update address details on Account'),e.getMessage());
            //System.debug('Exception Occurred: '+ e.getMessage());            
        }        
    }    

Please advise.

Thanks,
Krishna.
Raj VakatiRaj Vakati
Hi Krishna ,
To cover the catch block, fail your RRAddress__c  object insert or update and catch it with try and catch methods . Sample code is here 
try{
 RRAddress__c addr1 = new RRAddress__c();
 addr1.Employee__c =null ;
 insert addr1;
 }
 catch(Exception e){
 
 }


 
coolkrishcoolkrish
Thanks Raja for you reply but here Employee__c is not required field but addr1.Name field....I tried to make the Name field on address null but catch block is not getting coverage as the error messages are different.

I have put custom error in my catch block in the code.