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
ashu 6112ashu 6112 

catch block test coverage

public static Account insertIntoAccount(Account account){
		try{
			insert account;
			return account;
		}catch(Exception e){
		   string error = ExceptionLogger.createExceptionsRecord(e.getMessage(), 'DealReqContactController', e.getStackTraceString());
			throw new AuraHandledException(error);
			return null;
	   }
    }

Hi All, 
I have to cover code coverage of catch block.

Please help:

 
ashu 6112ashu 6112
I tried to cover the same by this :
try{
        DealReqContactController.insertIntoAccount(new Account(name='test1'));
      
        }catch (AuraHandledException e) {
            System.debug(e.getMessage());
            System.debug(e.getTypeName());
        }

But it is not covering the catch block, it is covering only the try block...
Balayesu ChilakalapudiBalayesu Chilakalapudi
Try like this,
@isTest
public Test{
   public static testmethod void test1(){
      Account a;
      DealReqContactController.insertIntoAccount(a);
   }
}
Let us know if it helps
 
Hemant_JainHemant_Jain
Raise some exception condition, so that account will not get inserted.

Below code might help
@isTest
public DealReqContactControllerTest{
   public static testmethod void testFailureCondition(){
      Account acc =new Account(name='testAccount');
      insert acc;
      DealReqContactController.insertIntoAccount(acc);
   }
}

Here we are trying to insert already inserted account, so it will give an exception and go to the catch block.

Kindly mark this as the best answer if this helps.
ashu 6112ashu 6112
Hi Bala, 

we dont need to write the test catch block in our test class..
Prithviraj_ChavanPrithviraj_Chavan
Hi,
There 1 trick I use but I dont recommend this..
write catch in single line so it will be automatically covered
ashu 6112ashu 6112
Hi Prithviraj_Chavan,

Dont getting y0our point, please gve suggestion.
Balayesu ChilakalapudiBalayesu Chilakalapudi
Just add these lines at the end of your test class
try{ 
     Account acc;
     DealReqContactController.insertIntoAccount(acc); 
 }catch (AuraHandledException e){ 
    System.debug(e.getMessage()); 
    System.debug(e.getTypeName()); 
}
Prithviraj_ChavanPrithviraj_Chavan
Hi ashu,
try to write body of catch block in single line ..
ashu 6112ashu 6112
In Main class or test class, I think you are saying in 'Main class'
Hemant_JainHemant_Jain
Hi Ashu,

Didn't the above solution given by me, work for you? Could you pls let me know what issue you faced for the above code for raising exception codition.
 
Prithviraj_ChavanPrithviraj_Chavan
Hi ashu In main class try to write catch body in single line and run test method it will cover that single line
eg. catch(Exception ex){  system.debug('ERROR Occurred   ::    '+Ex.getMessages()); return null; }