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
KevSnellKevSnell 

Test Exceptions

Hi All,

 

One thing I have yet to find the answer to is how do you test exceptions.  For example I have two exceptions one in a Class and the other in a Trigger, yet I can't seem to find the answer on how to test these.

 

If anyone can help here are the two different exceptions:

 

Apex Class:

catch(Exception ex)
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,ex.getMessage()));
}

 

Apex Trigger:

catch (DmlException de)
{
for ( integer i = 0; i < de.getNumDml(); i++ )
{
System.debug('Lead_Referral Error Inserting Lead Referral Objects: ' + de.getDmlMessage(i));
} 

 

Any help or guidance would really be appreciated.


Thanks

Kev 

 

Best Answer chosen by Admin (Salesforce Developers) 
Damien_Damien_

You need to do something that would cause them to fail.  For example lets say I have an object called 'My_Obj__c'.  It has a required field called 'Required__c'.  I also have an extension called 'MyCont'.

 

The below testmethod code will cause the upsert call to fail because I never set the required field.  This allows it to cover the items inside the catch block.  A similar such situation can be done for your trigger.  The trigger can vary how its done depending on what it is you are trying to do inside of it.

 

Testmethod code

MyCont cont = new MyCont(new My_Obj__c());
cont.mySaveMethod();

 

MyCont.mySaveMethod();

public void mySaveMethod()
{
	try
	{
		upsert myObjVarName;
	}catch (Exception e)
	{
		System.debug('this line gets hit from my test method!');
	}
}