Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Salesforce QA / Tester
medium

How do you test an Apex trigger?

Triggers fire automatically; testing them requires deliberate setup.

Test class structure:

`apex @isTest private class AccountTriggerTest {

@TestSetup static void setup() { // Create base test data Account a = new Account(Name='Test Account'); insert a; }

@isTest static void testInsertSetsIndustryDefault() { // Arrange Account a = new Account(Name='New Account');

// Act Test.startTest(); insert a; Test.stopTest();

// Assert Account inserted = [SELECT Industry FROM Account WHERE Id=:a.Id]; System.assertEquals('Technology', inserted.Industry); }

@isTest static void testBulkInsert() { List<Account> accounts = new List<Account>(); for (Integer i=0; i<200; i++) { accounts.add(new Account(Name='Bulk '+i)); } Test.startTest(); insert accounts; Test.stopTest();

// Assert all 200 processed correctly List<Account> inserted = [SELECT Id FROM Account WHERE Name LIKE 'Bulk %']; System.assertEquals(200, inserted.size()); }

@isTest static void testUpdateTriggersFollowUp() { Account a = [SELECT Id FROM Account LIMIT 1]; a.Status__c = 'Active';

Test.startTest(); update a; Test.stopTest();

// Assert downstream effect Task[] tasks = [SELECT Id FROM Task WHERE WhatId=:a.Id]; System.assertEquals(1, tasks.size()); } } `

Key patterns:

1. Bulk testing. Always test with 200 records to confirm bulkification.

2. `Test.startTest()` / `Test.stopTest()`. Reset governor limits; flush async.

3. Cover all DML events. Insert, update, delete (where applicable).

4. Cover all paths. Happy path, edge cases, error scenarios.

5. Use `@TestSetup`. Shared data setup; runs once per class.

6. Assert behavior, not just coverage.

7. Mock dependencies if trigger has callouts or relies on async.

8. Test recursion handling. If trigger has recursion guard, test it works.

Common pitfalls:

  • Single-record tests only. Doesn't catch bulk issues.
  • No bulk test. Trigger fails at 200 records in production.
  • Coverage tests, no assertions. Useless.
  • Fragile dependencies. @isTest(SeeAllData=true) — bad practice.

Senior QA insight: trigger tests are critical. Production code paths fail at scale; tests must catch this. Bulk testing is mandatory.

The senior framing: tests document trigger behavior. Future devs read tests to understand what trigger does.

Why this answer works

Senior. The bulk-testing emphasis and "tests document behavior" framing are mature.

Follow-ups to expect

Related dictionary terms