LaceySnr.com - Salesforce Development Posts by Matt Lacey

On Test Methods

Posted: 2010-04-14

I hate the test methods that need to be written in Salesforce. I can vaguely see how they're a good thing but to me they're nothing but a pain in the butt - the more error checking you put in your code the harder it is to get coverage, so if you do something like:

MyObject__c obj = new MyObject__c();
obj.Name = 'obj';

try
{
    insert obj;
}
catch(Exception e)
{
    // add an error message to the page
}

you're going to have a hard time to cover whatever code you put in the catch block. Granted an exception should probably never be thrown in 99% of these situations, but for those of us who write defensive code the coverage requirement can just seem like a twisted punishment for being careful.

When it comes to callouts things are no better. I usually create a private boolean called m_bIsTest which the test method can set to true (as it's in the same class) then use m_bIsTest to tell me if I need to fake the callout; I'm writing extra code which bypasses functionality just for the sake of these test classes. With careful coding this will never be an issue but it does strike me as an odd situation - who watches the watchmen?