0

The following Trigger is firing twice:

trigger AccountTrigger on Account ( before insert, after insert, before update, after update, before delete, after delete) {

    AccountTriggerHandler handle = new AccountTriggerHandler(trigger.new, trigger.oldMap);
    System.debug('AccountTrigger created a handler instance: ' + handle);
    // Currently the Trigger is firing twice with no obvious reason.
    
  if (Trigger.isBefore) {
    if (Trigger.isInsert) {
      handle.beforeInsert();
    } 
    if (Trigger.isUpdate) {
      // Call handler here!
    }
    if (Trigger.isDelete) {
      // Call handler here!
    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {
      // Call handler here!
    } 
    if (Trigger.isUpdate) {
      // Call handler here!
    }
    if (Trigger.isDelete) {
      // Call handler here!
    }
  }
}

The debug result is showing two handler instances. The weird thing is: The first one seems to be empty? How can that be? Debug Statements

EDIT 1: The Testcode:

@isTest
public class AccountTestTest {
@isTest
    public static void testAccountInsert() {
        // Insert an Account
        Account a = new Account(name='TestCustomer');
        insert a;
        
        Account queryAccount = [SELECT Account.id, Account.name FROM Account WHERE Id = :a.Id];
        System.debug('TEST RESULT: ' + queryAccount);
        System.debug('AccountTestTest completed.');
        // Actually test something...
    }
    
}

I know it's missing asserts, but for the sake of simplicity, I just tried this one.

coffee_bear
  • 31
  • 1
  • 8

1 Answers1

1

It's because of ”before insert”. At that stage ids haven't been generated yet. If you don't have any logic that fits into before insert best (complex validations? Field prepopulation?) remove that event?

eyescream
  • 18,088
  • 2
  • 34
  • 46