For some odd reason, the Trigger.new contains accounts that are null and when I save, an exception is raised:
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger: execution of BeforeInsert
caused by: System.NullPointerException: Attempt to de-reference a null object
Class.AccountTriggerHandler.CreateAccounts: line 4, column 1
Trigger.AccountTrigger: line 4, column 1: []
Here is my code:
trigger AccountTrigger on Account (before insert) {
if(Trigger.isInsert && Trigger.isBefore) {
System.debug(Trigger.new); //The trigger.new is not null but the accounts in it are
AccountTriggerHandler.CreateAccounts(Trigger.new);
}
}
The class
public class AccountTriggerHandler {
public static void CreateAccounts(List<Account> accounts) {
for(Account acct : accounts) {
if(acct.ShippingState.compareTo(acct.BillingState) != 0) {
acct.ShippingState = acct.BillingState;
}
}
}
}
The test class
@isTest
private class AccountTriggerTest {
static testMethod void testUpdateShippingState() {
//Arrange
List<Account> newAccounts = new List<Account>();
for(integer i = 0; i < 200; i++) {
Account acct = new Account(Name='Test Account' + i, BillingState='CA');
newAccounts.add(acct);
}
//Act
Test.startTest();
insert newAccounts;
Test.stopTest();
//Assert
List<Account> updatedAccounts = [SELECT Name, BillingState, ShippingState FROM Account WHERE BillingState = 'CA'];
for(Account acct : updatedAccounts) {
System.assertEquals('CA', acct.ShippingState, 'Whoops! The states are not the same!');
}
}
}
When I deactivate the trigger, an account is inserted successfully. That is the odd part.
What is wrong with the trigger?