Order of Execution (OoE): predictable sequence of operations on record save (validation, before-save flows, before triggers, save, after triggers, after-save flows, workflow rules, etc.).
When testing, you need to know:
- Which step fires first?
- Re-entry: does workflow update re-trigger anything?
- Field state at different points in execution.
Test patterns:
1. Test before vs after triggers.
`apex @isTest static void testBeforeTriggerUpdatesField() { Account a = new Account(Name='Test');
Test.startTest(); insert a; Test.stopTest();
// Before trigger should have set Industry Account inserted = [SELECT Industry FROM Account WHERE Id=:a.Id]; System.assertEquals('Default', inserted.Industry); } `
Before triggers can modify Trigger.new directly without DML.
2. Test after-trigger side effects.
After triggers run after database insert (record has Id). Test for child record creation, follow-up tasks, etc.
3. Test workflow re-entry.
Workflow field updates re-fire before/after triggers and validation rules. Confirm logic handles this:
`apex @isTest static void testWorkflowRefireGotcha() { Account a = new Account(Name='Test', Status__c='Active'); insert a;
// Confirm the field update from Workflow didn't cause unexpected behavior } `
4. Test validation rules.
`apex @isTest static void testValidationRuleBlocks() { Account a = new Account(Name=null); // Required field missing
try { insert a; System.assert(false, 'Should have thrown'); } catch (DmlException e) { System.assert(e.getMessage().contains('Required')); } } `
5. Test order between competing triggers.
When multiple triggers (or trigger + flow) fire on same object, order is undefined. Best practice: one trigger per object. If multiple exist, test that the right one wins.
6. Test async after commit.
Outbound Messages, async Apex (@future, Queueable) fire AFTER commit-2. Use Test.startTest()/stopTest() to flush.
Common pitfalls:
- Assuming order without testing.
- Race conditions in multiple triggers.
- Forgetting workflow re-entry.
- Not flushing async in tests.
Senior QA insight: OoE bugs are subtle. Tests must explicitly cover the orderings expected. Most production bugs are timing / order issues.
The senior framing: Salesforce's OoE is well-defined; your code must respect it. Tests verify both.
