1

I have a simple trigger that runs on Account update, and the only logic is a check to whether or now BillingPostalCode changes or not.

This is my code:

trigger ZipCodeUpdated on Account (before update) {
    for(Integer i=0; i<Trigger.new.size(); i++){
        if(Trigger.new[i].BillingPostalCode != Trigger.old[i].BillingPostalCode){
            ZipCodeUpdatedHelper.InitialCheck(Trigger.new, Trigger.old);
        }
    }
}

I'm not sure how the test class should look like, so any help would be appreciated.

3
  • Unit tests in Salesforce will generally look the same no matter what it is you're trying to test. There are a few exceptions, but this trigger isn't one of them. If you haven't already looked through salesforce.stackexchange.com/questions/244788/…, you should. It also contains a link to the Apex Testing module on trailhead (which will help you with the general structure of tests).
    – Derek F
    Commented Sep 24, 2021 at 18:15
  • Also, you should consider using the Trigger.oldMap context variable to access the old record (allowing you to use for(Account acct :trigger.new) instead of for(Integer i=0; i<Trigger.new.size(); i++)). You also probably don't want to be calling your ZipCodeUpdatedHelper.InitialCheck() method on every iteration (and not passing all trigger records to it when you do). Having your loop create Lists of records to process, and then calling your method outside of the loops (passing the Lists your loop populated) is a better approach.
    – Derek F
    Commented Sep 24, 2021 at 18:20
  • @DerekF thanks, that's valuable knowledge, I'll take that into consideration! Commented Sep 24, 2021 at 19:22

1 Answer 1

2

At a basic level, you simply create a record, then change the value in memory, and update:

Account record = new Account(BillingPostalCode='12345',...);
insert record;
record.BillingPostalCode = '54321';
Test.startTest();
update record;
Test.stopTest();
// remember to check to make sure your logic ran.

Not the answer you're looking for? Browse other questions tagged .