+ Start a Discussion
Chris987654321Chris987654321 

Writing test methods to execute a Catch

If I have a try/catch block which does an update to the Database, how do I write a test method to execute the catch? It seems I would have to force the update to fail? 
 

//Save the information entered in by the student

try {

//save the changes that the student made on the form

update enrollment;

}

 

catch(System.DMLException e) {

ApexPages.addMessages(e);

System.debug(e);

return null;

}

 

 
Message Edited by Chris987654321 on 08-09-2009 07:21 PM
Message Edited by Chris987654321 on 08-09-2009 07:23 PM
CRM JediCRM Jedi
I don't like this but I would normally throw an error to cover the exceptions. This is controlled by a variable so that the error will only be thrown when testmethod is running.
wesnoltewesnolte

Hey

 

There are a few ways to force a DMLException on update. I don't know all of them but some are:

 

1. Duplicate a unique field in a record eg. insert a record with a certain name, and then try update another with the same name

2.  Don't specify a required field.

3. Delete the record before you try the update.

4. Specify the incorrect field type eg. try to put a string in a number field (not 100% sure this is a DML exception. Might be some sort of cast exception).

 

Ask yourself what conditions did you anticipate in writing this exception, and then try fake them.

 

Cheers,

Wes