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

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 =[0];

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





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){



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






Error : Check Setting

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.