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
DarrellDDarrellD 

Should Test Class Have Try Catch Blocks?

From a best practice perspective, should the test class have any Try...Catch blocks or are all of these in the production classes and Triggers?

 

It seemed to me like the test class should not have Try...Catch blocks but I keep seeing these in examples.  Isn't purpose of these so the code catches them?

 

Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Andrew WilkinsonAndrew Wilkinson

I have used these for this purpose.

 

http://andrewwilkinsonsf.blogspot.com/2012/10/unit-test-for-adderror-method.html

 

Also if you ever queried data like recordtype or profile for use in your unit test. Those could be in a try catch. But for actual testing of a class the above example is when I have used them.

All Answers

Andrew WilkinsonAndrew Wilkinson

I have used these for this purpose.

 

http://andrewwilkinsonsf.blogspot.com/2012/10/unit-test-for-adderror-method.html

 

Also if you ever queried data like recordtype or profile for use in your unit test. Those could be in a try catch. But for actual testing of a class the above example is when I have used them.

This was selected as the best answer
Anil MeghnathiAnil Meghnathi

In test method during the insertion of any object if you get any error,that tst method will be failed.But if you have written that insert  operation in try catch then test method will not fail,and rest of the test will be execute

 

Thanks

Anil

hemantgarghemantgarg

If we use try catch block in test classes, then error/exception will be caught, in such cases your test class should show it failed but due to catch it will show successful, so it is not a best practice, I think.