Friday, February 17, 2012

Disabling a Salesforce trigger when setting up test case data

When setting up test case data from an Apex test method I needed a technique to disable triggers that were firing and causing a LimitException: "Too many SOQL queries: 101". The triggers weren't the target of the test case and in some scenarios could cause the test method to fail before the target method and assertions could be called.

I didn't want to disable the triggers for every test case. Just in certain cases as the required data was being set up.

Option 1

Wrap the setup phase code of the test method with System.runAs().

In the trigger do nothing if Test.isRunningTest() and UserInfo.getName() equals the specified user that the testMethod specifies in the runAs().

If you are creating the User as part of the test case ensure the Username is sufficiently unique. I've had the DUPLICATE_USERNAME exception in production and not the sandbox as the username has to be unique across all Salesforce instances.

Option 2

Alternatively, create a class with a static boolean variable that can be used to toggle the trigger functionality on and off.

See Also:

No comments:

Post a Comment