function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFTerrSFTerr 

Apex Test Classes: "Attempt to de-reference a null object" error

Hi, I wrote a trigger and a test class, but when testing I get below error: 

System.DmlException: Update failed. First exception on row 0 with id 003M000000Zc1NaIAJ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PopulateContactAreaCode: execution of BeforeUpdate
caused by: System.NullPointerException: Attempt to de-reference a null object
Trigger.PopulateContactAreaCode: line 5, column 1: []

Trigger:
trigger PopulateContactAreaCode on Contact (before insert, before update) {

    for(Contact contact : Trigger.new)
    {
        string AreaCode = CountryRegion__c.getInstance(contact.MailingCountry).Area_Code__c;
        contact.Area_Code__c = AreaCode;
    }
}

test class:
@isTest
public class PopulateContactAreaCodeTest
{
    static testMethod void attTriggerTest1()
    {
        test.startTest();
        Account acct = new Account(id = '001M000000iLhTL', Name = 'Test Account ', Mailing_Country__c = 'Afghanistan');
        update acct;      
        Contact con = new Contact(id = '003M000000Zc1Na', LastName = 'Test Contact', Account = acct, Email = 'test@test.com', Mailing_Country__c = 'Afghanistan', MailingCountry = 'Afghanistan');
        update con;
        delete con;
        test.stopTest();
    }
}

any idea what I added wrong?

thank you in advance
Best Answer chosen by SFTerr
James LoghryJames Loghry

Because you're running a unit test, it doesn't see any data, and therefore no custom settings exist.  You'll need to insert the custom setting before you insert the Contact record.  Here's an example:
 

static testMethod void attTriggerTest1()
    {
        insert new CountryRegion__c(Name='Afghanistan',Area_Code__c='123');

        test.startTest();
        Account acct = new Account(id = '001M000000iLhTL', Name = 'Test Account ', Mailing_Country__c = 'Afghanistan');
        update acct;     
        Contact con = new Contact(id = '003M000000Zc1Na', LastName = 'Test Contact', Account = acct, Email = 'test@test.com', Mailing_Country__c = 'Afghanistan', MailingCountry = 'Afghanistan');
        update con;
        delete con;
        test.stopTest();
    }

All Answers

James LoghryJames Loghry

Because you're running a unit test, it doesn't see any data, and therefore no custom settings exist.  You'll need to insert the custom setting before you insert the Contact record.  Here's an example:
 

static testMethod void attTriggerTest1()
    {
        insert new CountryRegion__c(Name='Afghanistan',Area_Code__c='123');

        test.startTest();
        Account acct = new Account(id = '001M000000iLhTL', Name = 'Test Account ', Mailing_Country__c = 'Afghanistan');
        update acct;     
        Contact con = new Contact(id = '003M000000Zc1Na', LastName = 'Test Contact', Account = acct, Email = 'test@test.com', Mailing_Country__c = 'Afghanistan', MailingCountry = 'Afghanistan');
        update con;
        delete con;
        test.stopTest();
    }
This was selected as the best answer
SFTerrSFTerr
Thank you so much, I did not think of that
SFTerrSFTerr
Can I also ask you why similar trigger for leads does not recognise the custom setting? 
 
trigger PopulateLeadAreaCode on Lead (before insert, before update) {

    for (Lead newLead : Trigger.new)
    {
        string AreaCode = CountryRegion__c.getInstance(Lead.Country). Area_Code__c;
        lead.Area_Code__c = AreaCode;
    }
}

Error: Compile Error: Variable does not exist: CountryRegion__c at line 5 column 27
mahika agrawalmahika agrawal
Hi @james Loghry,

I have the below trigger and trigger handler could you help me as I am getting two errors: 
1. Attempt to derefrence a nullObject.
2. Assertion Failed.

if(Trigger.isAfter && Trigger.isInsert){ 
               IFB_PayInSlipTriggerHandler.IncreasePISBalanceoncreation(Trigger.New);
    }

Handler Class: 
public static void IncreasePISBalanceoncreation(list<IFB_PayInSlips__c> payInSlips){
        for(IFB_PayInSlips__c ObjPIS: payInSlips){
             //check the status if it is PIScreated 
           IFB_CashVaultService.MaintainVaultBalance(ObjPIS.IFB_Status__c , ObjPIS.IFB_TotalAmount__c, ObjPIS.OwnerId);
 }

and have again we have service class which is calling MaintainVaultBalance.

Let me know if any further details are required.

Thanks in advance.
jacab smithjacab smith

when a variable or object that was expected to have a value is actually null. This error can happen when trying to access a variable or object that has not been instantiated, or when trying to access a variable or object that has been set to null.

One common cause of this error in Apex Test Classes is when test data is not properly set up. For example, if a test method is trying to access a record that has not been inserted into the database, it will result in a null object error.
https://cutt.ly/g9jc90y To avoid this, it's important to make sure that all necessary test data is properly set up and inserted into the database before running the test methods.

Another common cause of this error is when a variable or object is not properly initialized or instantiated. For example, if a variable is declared but not given a value, it will be `null` and attempting to access it will result in a `null` object error. To avoid this, it's important to make sure that all variables and objects are properly initialized or instantiated before they are used.

Additionally, when working with complex data structures, it is important to check for null values before trying to access them. Apex provides the null keyword that can be used to check if a variable is null or not, if it is null it will not execute the code inside the if block.
To resolve this error, it's important to identify the specific line of code where the error is occurring and then determine what variable or object is causing the problem. Once the problem has been identified, it can be fixed by properly.

author - http://www.moditaliamagazine.com/cookiebar/ok_cookie.asp?url=https%3A%2F%2Ffinancemantras.com