+ Start a Discussion
HelloSanHelloSan 

how to write the test class to cover try catch block 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.ServiceIncement __c = 'Yes';   
}
else
{
oppty.ServiceIncement __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”');
          }  
       }
 }
}
AshlekhAshlekh
Hi,

You have to throw exception explicitly. 

You can use Test.isRunningTest() method to know that code is running in test mode.

Use below code.

If(Test.isRunningTest())
{
   Integer x = 1/0; //Controller will reach here only when code is runninging test mode and will throw exception e.


-Thanks
Ashlekh Gera
MagulanDuraipandianMagulanDuraipandian
Check this - http://www.infallibletechie.com/2015/11/how-to-cover-catch-block-in-test-class.html
HelloSanHelloSan
Hi Ashlekh Gera
I have included below code in trigger

If(Test.isRunningTest())
{
   Integer x = 1/0; //Controller will reach here only when code is runninging test mode and will throw exception e.

 i have run the test class, the exception is thrown explicitly the test method is failed and in the error message is giving the error message in catch block.
do you have any solution to get the method passed with above code in apex trigger.