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
Kristiana GrangerKristiana Granger 

How to cover catch block for the test class?

Hi, All
I am new to salesforce, can anyone help me to get 100% coverage please 


public class MyContactListController 
{
    @AuraEnabled
    public static List<Contact> getContacts(Id recordId) 
    {
        List<Contact> conList = new List<Contact>();
        try{
            System.debug('--'+recordId);
            conList = [Select Id, FirstName, LastName, Email, Phone From Contact Where AccountId = :recordId];
            System.debug('conlist result----> '+conList);
        }
        catch(Exception e){
            System.debug('inside catch Block  -> '+e.getMessage());
        }
        return conList;
    }
}



-----------------------------------------
TestClass
-----------------------------------------
@isTest
public class MyContactListControllerTest {
   
    static testMethod void getContactsTest(){
        Account ac = new Account(Name='Name1');
        Insert ac;
        List<Account> acList = [select id, name from Account where id!=NULL];
        System.assertEquals(true,acList.size()>0);
        MyContactListController.getContacts(acList[0].id);
        List<Case> case_Obj  =  [SELECT Id,CaseNumber,AccountId From Case WHERE AccountId=:acList[0].Id LIMIT 10];
       
        MyContactListController.getContacts(acList[0].Id); 
      
    }
}
Suraj Tripathi 47Suraj Tripathi 47
Hi,

You can cover catch by not giving the required field that is needed when some operation is performing in Apex class. Test class will cover catch block whenever the error will occur in the main class. Like this:-
@isTest
public class MyContactListControllerTest {
   
    static testMethod void getContactsTest(){
        Account ac = new Account(Name='Name1');
        Insert ac;
        MyContactListController.getContacts(ac.Id); 
     
    }
}

This will cover catch as there is no contact with the account.

Please mark it as Best Answer if it helps you.

Thanks & Regards
Suraj Tripath
i
CharuDuttCharuDutt
Hii Kristiana Granger
Try Below Code

Made Some Changes Which Are In Bold
public class MyContactListController 
{
    @AuraEnabled
    public static List<Contact> getContacts(Id recordId) 
    {
        List<Contact> conList = new List<Contact>();
        try{
            System.debug('--'+recordId);
            conList = [Select Id, FirstName, LastName, Email, Phone From Contact Where AccountId = :recordId];
            System.debug('conlist result----> '+conList);

           if(Test.isRunningTest())
			{
				throw new dmlException();
			}    
        }
        catch(dmlException e){
            System.debug('inside catch Block  -> '+e.getMessage());
        }
        return conList;
    }
}


Test Class

@isTest
public class MyContactListControllerTest {
   
    static testMethod void getContactsTest(){
        Account ac = new Account(Name='Name1');
        Insert ac;

      
        contact con = new Contact();
        Con.FirstName = 'test';
            Con.LastName = 'Con';
            Con.AccountId = ac.Id;
            Con.Email = 'Test@test.Com';
            Con.Phone = '0123456789';
            
          
        insert Con;
        MyContactListController.getContacts(ac.Id); 
      
    }
}
Please Mark It As Best Answer If It Helps
Thank You!

 
Kristiana GrangerKristiana Granger

@Suraj Tripathi 47 - Thank you for Quick reply, Can you please suggest other way as with given code not able to achieve 100%

@CharuDutt - Thank you for Quick and detailed reply, I see when I try to save given code (in bold) it wont allow me to save, but yea I am exploring that method, its good to know the new method
CharuDuttCharuDutt
HII Kristina 
Can you please Tell why It's Not Allowing To Save
Kristiana GrangerKristiana Granger
@CharuDutt
its giving below error -
"Method does not exist or incorrect signature: void isRunningTest() from the type Test"
CharuDuttCharuDutt
Hii kristiana
​​​​​​It's Because May be There's A Class Named test In Yours ORG That's Why It's Not Letting You Save The Class 
I There's Another Class With The Name Test Change That Class Name
AbhinavAbhinav (Salesforce Developers) 
Hi Kristiana,

You can try suggestion posted in below link

https://salesforce.stackexchange.com/questions/57344/how-to-cover-catch-statement-in-test-class

Thanks!
mukesh guptamukesh gupta
Hi Kristiana,

Please use below code for 100% code coverage  without changes in your main class
 
@isTest
public class MyContactListControllerTest {
   
    static testMethod void getContactsTest_Try(){
        Account ac = new Account(Name='Name1');
        Insert ac;
        List<Account> acList = List<Account>();
        //System.assertEquals(true,acList.size()>0);
		 Contact c=new Contact(
		    AccountId = ac.Id,
            FirstName='fname',
            LastName = 'lname',
            Email = 'email@gmail.com',
            Phone = '9743800309'); 
        insert c; 
        MyContactListController.getContacts(acList[0].id);
        //List<Case> case_Obj  =  [SELECT Id,CaseNumber,AccountId From Case WHERE AccountId=:acList[0].Id LIMIT 10];
       
        MyContactListController.getContacts(acList[0].Id); 
      
    }
	static testMethod void getContactsTest_Catch(){
        Account ac = new Account(Name='Name1');
        Insert ac;
        List<Account> acList = List<Account>();
        //System.assertEquals(true,acList.size()>0);
		 Contact c=new Contact(
		    AccountId = ac.Id,
            FirstName='fname',
            LastName = 'lname',
            Email = 'email@gmail.com',
            Phone = '9743800309'); 
        insert c; 
        MyContactListController.getContacts(acList[0].id);
        //List<Case> case_Obj  =  [SELECT Id,CaseNumber,AccountId From Case WHERE AccountId=:acList[0].Id LIMIT 10];
       
	    List<String> ids = new List<String>();
        MyContactListController.getContacts(ids); 
      
      
    }
}

if you need any assistanse, Please let me know!!


Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
Veronin SkadvizVeronin Skadviz
i think lulubox app was has the same issue
https://lulubox.top/
pkulkarnipkulkarni
Hello, I might be late, but this is working for me, may help you, thanks

//Main Class
public class AccountHandler{
    public static void insertAccount(Account acc){
        try{
            insert acc;
        }catch(DMLException dex){
            system.debug('dml exception occured: ' + dex.getMessage());
        }
    }
}

//Test Class
@IsTest
public class AccountHandlerTest{
    public static testMethod void insertAccountTest(){
        //Cover try block
        Account acc = new Account(Name = 'Test Account');
        AccountHandler.insertAccount(acc);
        
        //Cover catch block
        Account accnt = new Account(); //drop required field to throw exception deliberately
        
        //catch exception you are getting in test class as shown below
        try{
            AccountHandler.insertAccount(accnt);
        }catch(DMLException dex){
            System.debug ('all right' + dex.getMessage());
            return;
        }
        System.assert(false, 'a dml exception was expected but was not thrown');
    }
}