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
birdofpreybirdofprey 

How to create a test method for catches?

In my apex i have serveral catches, which I can't seem to be able to get an test method to cover it durning my test

And the Exception it would throw and catch is an "QueryException" Error.

trigger Signer on Form__c (before insert, before update) {
	
	Form__c F = trigger.new[0];
            ...
	try{     
	    ...

	}catch (Exception e) {
		Trigger.new[0].Signer__c.addError('Error : Check Setting');
	}


    

 

 

Starz26Starz26

In your test method,

 

you would have to insert/update a record that would cause the DML error to occur.

 

Then you can check it in the test method like this if you so desire: (may require debugging as doing it from memory)

 

Database.saveResult[] results = New Database.SaveResult();

 

results = database.insert( xxxx, false);

 

for(Database.SaveResult sr : results){

 

if(!sr.isSuccess){

system.assertEquals('Error : Check Setting',sr.getDMLMessage(0));

}

 

 

}

 

Error : Check Setting
Sam27Sam27

I agree,

 

For test to cover the catches you intentionally have to force an exception in the try block so that it goes to catch block and hence catch block code is covered.

Since you haven't provided what is happening in that try block I wont be able to be specific as how to force an exception there.

One easy way is to pass the wrong parameter or declaring some variable as null , if it's an SOQL query pass the wrong variables.

I hope that will help.