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
HelloSanHelloSan 

how to write the test class to cover code coverage for try catch block written in apex trigger

trigger UpdateOpptyOnServiceupdate on Servic__c (after insert, after update)
{
Set<Id> oppid = new Set<Id>();
Map<Id,List<Service __c>> mpoppservice=new Map<Id,List<Service __c>>();
List<Opportunity> updatelist =  new list<Opportunity>();
String str =  null;
for(Service__c s:trigger.new)
{
if(s.Opportunity__c != null){
oppid.add(s.Opportunity__c);
}
List<Opportunity> opplist = [Select id,ServiceIncrement__c ,(Select id,Expired _Years__c from Service__r) From Opportunity where Id IN:oppid];

For(Opportunity opp:opplist)
{
mpoppservice.put(opp.id,opp. Service__r);   
}
for(Opportunity oppty:opplist)
{
Integer i = 0;   
Id temp = oppty.id;
List<Service __c>  slist= mpoppservice.get(temp);   
if(slist.size()!=0)
{
for(Service__c s1: slist)
{
str =s1. Expired _Years__c;
if(str != '<1' && str != null)   
{
i = 2;
}
if(i==2)   
{
oppty.ServiceIncrement __c = 'Yes';   
}
else
{
oppty.ServiceIncrement __c = 'No';   
}   
updatelist.add(oppty);   
}   
}
}
      try
        {
          update updatelist;
         }catch(Exception e) 
         { 
          for(Service__c s : trigger.new)
          {
          Id opid= s.Opportunity__c;
          Opportunity op = [select id,name from Opportunity where id=:opid];
          s.addError('“Updating opportunity associated to this service,but could not because the required fields are missing on opportunity”');
          }  
       }
 }
}
ManojjenaManojjena
Hi Hellosan,
Try with below code .Try to add mandatory fields in each level .
 
@isTest
public class TestUpdateOpptyOnServiceupdate{
  private static testMethod void unitTest(){
     Account acc=new Account();
	 acc.Name='TestAccount';
	 Insert acc;
	 System.assertEquals('TestAccount',acc.Name);
	 Opportunity opp=new Opportunity();
	 oppp.Name='TestOpportunity';
	 opp.closedDate=System.Today();
	 opp.StageName='Active';//Replace any pick list value from your org .
	 opp.AccountId=acc.Id;
	 insert opp;
	 System.assertEquals('TestOpportunity',opp.Name);
	 Service__c ser=new Service__c();
	 ser.Expired _Years__c=Add some value as per you;
	 ser.Opportunity__c=opp.Id;
	 insert ser;
	 update ser;
  
  }

}
For some tips in test class you can follow belwo link .
http://manojjena20.blogspot.in/2015/06/tips-and-tricks-for-test-class.html 

I think you need to modify your trigger as well as it is not bulkified .
Thanks
Manoj

 
RAM AnisettiRAM Anisetti
Hi try this way...

In Test Class

static testMethod void TestMethodOne(){
  a) insert opportunity record
  b) insert Service__c record

}

static testMethod void TestMethodTwo(){
  a) insert opportunity record(u need to give test data to execute Exception Block)
  b) insert Service__c record in try block

   add Below lines

  
try {
    insert Service__c record;
    System.assert(false, 'exception expected');
} catch (Exception e) {
    String message = e.getMessage();
    System.assert(message.contains('Updating opportunity associated to this service,but could not because the required fields are missing on opportunity'), + message);
}



​}

 
HelloSanHelloSan
Hi Manoj
with the above sample code there is no coverage for catch block and the code coverage remain same as previous.
ManojjenaManojjena
hi Hellosan,
Please post your test code so that it will be easy to modify .
Vasundhara Velgoti 4Vasundhara Velgoti 4
Hi Manoj,

Can you please help me with my test code catch block coverage:

Trigger:

trigger POTriggerUpdate on PurchaseOrder__c (after insert, after update) {
    
     //Creating Project Plan in PurchaseOrder__c
    
     if(((trigger.isUpdate) && trigger.isAfter) || test.isRunningTest())
    {
       
    try
     {
      
           POTriggerLogic.afterInsertAfterUpdateLogic(trigger.new,trigger.oldMap,true);  
      }
      catch(DMLException e)
      {
         
      trigger.new[0].addError('Updation not possible because '+ e.getMessage());
          
     }
        
    }
    //End of Update Project plan in PurchaseOrder__c 

}

Testclass:

@isTest
public class Test_POTriggerUpdate {
    
     @isTest static void unittest(){
       Krow__Project__c kp = new Krow__Project__c();
          kp.Id=kp.Id;
       
        insert kp;
        Krow__Task__c kt = new Krow__Task__c();
        kt.Id=kt.Id;
        kt.Name='test';
        kt.Krow__Start_Date__c = Date.today();
        kt.Krow__Due_Date__c   = Date.today();
        kt.Krow__Project__c    = kp.Id;
        
        kt.Krow__Parent_Task__c= null;
        kt.Actual_Due_Date__c  = null;
        kt.Krow__Project_Phase__c=false;
        kt.Create_Task_Assignment__c=true;
        insert kt;
           PurchaseOrder__c po                                   =  new PurchaseOrder__c();
                          
                          po.Name                              = 'Test order'; 
                           po.Status__c                         = 'Draft';
                          po.Engagement_Plan_Create__c         = false;
                          po.Engagement_Plan_Template__c       = kp.Id;
                          po.Engagement_Plan_Update__c         = false;
                          po.Engagement_Plan_Update_Template__c= kp.Id;
                         // po.Engagement_Plan__c                = opp.Engagement_Plan__c;
                   insert po;
                          po.Name                              = 'Test order1';
                         
                          po.Status__c                         = 'GM Approval Pending';
                          po.Engagement_Plan_Create__c         =  true;
                          po.Engagement_Plan_Update__c         = true;
                          po.Engagement_Plan_Template__c       = kp.Id;
                          po.Engagement_Plan_Update_Template__c= kp.Id;
                          //po.Engagement_Plan__c                = null;
                update po;

       
       
        }
  @isTest static void unittest2(){
    
      try{
          Krow__Project__c kp = new Krow__Project__c();
          kp.Id=kp.Id;
          insert  kp;
           PurchaseOrder__c po                                   =  new PurchaseOrder__c();
                          
                          po.Name                              = 'Test order'; 
                           po.Status__c                         = 'Draft';
                          po.Engagement_Plan_Create__c         = false;
                          po.Engagement_Plan_Template__c       = kp.Id;
                          po.Engagement_Plan_Update__c         = false;
                          po.Engagement_Plan_Update_Template__c= kp.Id;
                         // po.Engagement_Plan__c                = opp.Engagement_Plan__c;
                   insert po; 
          System.assert(true,'exception expected');
      }
      catch(Exception e){
          String message=e.getMessage();
          System.assert(message.contains('Updation not possible because'),+message);
      }
      
      
  }
        
        
    
}