[SalesForce] Apex Test Class – Can You CRUD Without Firing Triggers – On Purpose

Is there anything built into Apex that lets one perform a CRUD operation on an SObject and suppress the related firing of any Apex Trigger / Workflow Rule / Process Flow?

(Similarly to the way one can spoof a create date, spoof the run-as user, etc.)

I've written some "helper" code to support a variety of trigger handlers. Since this code is called from the various trigger handlers, it actually has pretty good coverage without even trying to test it in a "pure" fashion.

But I'd like to give it its own test – that way, I know if my "helper" code actually does what I think it does, plus I can turn off triggers and still have coverage.

To exercise the "helper" code, some test records of the types it deals with have to exist. So my new test class has to insert them into the database.

However, that means I'll be invoking the triggers on all those SObject types, making it hard to tell just how much my new code is directly responsible for working the "helper class."

I suppose I could turn those triggers off for a few hours while I write the new test class, but that's annoying – and feels less cool.

Thanks!

Best Answer

Out of the box? No. But there are a few strategies you can implement. The simplest for triggers (and what I use) is to add a bypass flag in each handler.

public with sharing class MyTriggerHandler
{
    @TestVisible static Boolean bypassTrigger;

    public void beforeInsert()
    {
        if (bypassTrigger) return;

        // do stuff
    }
}

I have one handler per object, so it's pretty simple in my tests.

static testMethod void testSomething()
{
    AccountTriggerHandler.bypassTrigger = true;
    // insert accounts
    AccountTriggerHandler.bypassTrigger = false;

    ContactTriggerHandler.bypassTrigger = true;
    // insert contacts
    ContactTriggerHandler.bypassTrigger = false;
}

You can add granularity (at the cost of complexity) to taste with this pattern. For your needs, it sounds like a top level flag is ample.


A common strategy for Workflow Rule or Process Builder is to add a dummy checkbox that you can uncheck to disable them. Then in each, you have to make sure the criteria include NOT(Checkbox__c). I would have reservations about such a strategy if someone wanted me to implement it though, and seek workarounds specific to the situation.

Related Topic