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
Gaurav Shukla 61Gaurav Shukla 61 

I am getting error due to which my test class is getting failed System.NullPointerException: Attempt to de-reference a null object


public class ShareholderCompanyTriggerHandler {
    
    public static final Integer MAXIMUM_PERCENTAGE_OF_OWNERSHIP = 100;
    
    public static final String ERROR_MESSAGE_FOR_PERCENTAGE = 'Total Shareholding Percentage cannot be greater than 100% for this application.';
    
    public static ID ShareholderCompanyRecTypeId = RecordTypeHelper.getIdByDeveloperName(
                                                   Consts.Shareholder.getDevName(),
                                                   Consts.Shareholder.RecordTypes.Shareholder_Company);    
    
    //methods invocation for after event on Insert operation
    public static void onAfterInsert(List<Shareholder_Company__c> shareholderList) {
        validatePercentageOfOwnershipField(shareholderList);
    }
    
    //methods invocation for after event on Update operation
    public static void onAfterUpdate(Map<Id,Shareholder_Company__c> oldShareHolderMap, Map<Id,Shareholder_Company__c> newShareHolderMap) {
        validatePercentageOfOwnershipField(oldShareHolderMap,newShareHolderMap);
    }
    

    //method for checking overall percentage of ownership on application object
    //related to it's child object contact and shareholdercompany
    //count all contact records and shareholder company records of shareholder recordtype
    //on insertion of shareholder company object record
    //display error if overall percentage beyond 100%
    private static void validatePercentageOfOwnershipField(List<Shareholder_Company__c> shareholderList) {
                
        Set<ID> applicationIDSet = new Set<ID>();
        for(Shareholder_Company__c company : shareholderList) {
            if(company.RecordTypeId == ShareholderCompanyRecTypeId && company.Percentage_of_Ownership__c != null) {
                applicationIDSet.add(company.Application__c);
            }
        }
        
        Decimal AggregatePercentageOfOwnerShip;
        AggregatePercentageOfOwnerShip = TriggerHandlerUtil.getAllContactsAndShareHolderCompanyRecordsFromApplicationRecord(ApplicationIdSet);
        for(Shareholder_Company__c company : shareholderList) {
            if(AggregatePercentageOfOwnerShip > MAXIMUM_PERCENTAGE_OF_OWNERSHIP) {
                try {
                      company.Percentage_of_Ownership__c.addError(ERROR_MESSAGE_FOR_PERCENTAGE);
                    }
                catch(Exception e) {}
            }
        }
    }
    

    //method for checking overall percentage of ownership on application object
    //related to it's child object contact and shareholdercompany
    //count all contact records and shareholder company records of shareholder recordtype
    //on updation of shareholder company object record
    //display error if overall percentage beyond 100%
    private static void validatePercentageOfOwnershipField(Map<Id,Shareholder_Company__c> oldShareHolderMap, Map<Id,Shareholder_Company__c> newShareHolderMap) {      
        List<Shareholder_Company__c> shareholderList = newShareHolderMap.values();
        Set<ID> ApplicationIDSet = new Set<ID>();
        for(Shareholder_Company__c company : shareholderList) {
            if(
                (company.RecordTypeId == ShareholderCompanyRecTypeId && company.Percentage_of_Ownership__c != null) &&
                (
                    (company.Percentage_of_Ownership__c != oldShareHolderMap.get(company.Id).Percentage_of_Ownership__c) || 
                    (company.Application__c != oldShareHolderMap.get(company.Id).Application__c)
                )
            ) {
                ApplicationIDSet.add(company.Application__c);
              }
        }
        
        Decimal AggregatePercentageOfOwnerShip;
        AggregatePercentageOfOwnerShip = TriggerHandlerUtil.getAllContactsAndShareHolderCompanyRecordsFromApplicationRecord(ApplicationIdSet);
        for(Shareholder_Company__c company : shareholderList) {
            if(AggregatePercentageOfOwnerShip > MAXIMUM_PERCENTAGE_OF_OWNERSHIP) {
                try {
                      company.Percentage_of_Ownership__c.addError(ERROR_MESSAGE_FOR_PERCENTAGE);
                    }
                catch(Exception e) {}
            }
        }
    }
}
=====================================================

//test class for shareholdercompanytriggerhandler class

@IsTest
public class ShareholderCompanyTriggerHandler_Test {
    
    @IsTest
    private static void test_shareholdercompanyPercentage() {
        Consts.Contact_RecordTypes contactRTs = new Consts.Contact_RecordTypes();
        String contactRT = RecordTypeHelper.getIdByDeveloperName('Contact', contactRTs.Acquiring);
        
        Application__c application = TestUtil.createTestApp2();
        if(Application!= null){
            insert application;///////Error in this line 
        }
        system.debug('Application:::::::::'+application);
        //Creating Contact records
        List<Contact> contactsToInsert = new List<Contact>();
        for(Integer i=0; i<10; i++){
            Contact contact1 = new Contact(
                accountcontact__c = true,
                PassportNumber__c = '12345678qwertyuiop',
                PassportExpirationDate__c = Date.today() + 100,
                LastName = 'Test1',
                Nationality__c = 'Indian',
                MobilePhone = '97121333131',
                RecordTypeId = contactRT);            
            Integer randomNumber = Integer.valueof((math.random() * 10));
            if(randomNumber<3)
                Contact1.PercentageOfOwnership__c = 10;
            else if(randomNumber > 3 && randomNumber <=5)
                Contact1.PercentageOfOwnership__c = 30;
            else if(randomNumber > 5 && randomNumber <=8)
                Contact1.PercentageOfOwnership__c = 20;
            else 
                Contact1.PercentageOfOwnership__c = 130;
            contactsToInsert.add(contact1);            
        }  
        Database.insert (contactsToInsert,false);
        for(Contact contact: [Select id,PercentageOfOwnership__c From Contact WHERE PercentageOfOwnership__c!= null ]){
            system.debug('Percentage:::::::::'+contact.PercentageOfOwnership__c);
            System.AssertEquals(true,contact.PercentageOfOwnership__c<100);
        }
        //Creating Shareholder records
        List<Shareholder_Company__c> shareholderCompanyToInsert = new List<Shareholder_Company__c>();        
        Id ShareHolderComRecordTypeId = RecordTypeHelper.getIdByDeveloperName(Consts.Shareholder.getDevName(), Consts.Shareholder.RecordTypes.Shareholder_Company);
        for(Integer j=0; j<10;j++){
            Shareholder_Company__c shareholder1 = new Shareholder_Company__c();
            shareholder1.RecordTypeId = ShareHolderComRecordTypeId;
            Integer randomNumber = Integer.valueof((math.random() * 10));
            if(randomNumber<3)
                shareholder1.Percentage_of_Ownership__c = 10;
            else if(randomNumber > 3 && randomNumber <=5)
                shareholder1.Percentage_of_Ownership__c = 30;
            else if(randomNumber > 5 && randomNumber <=8)
                shareholder1.Percentage_of_Ownership__c = 20;
            else 
                shareholder1.Percentage_of_Ownership__c = 130;
            shareholder1.Trade_License_number__c = '4824';
            shareholder1.Name = 'test shareholder company';
            shareholder1.Date_of_Establishment__c = Date.today() - 20;
            shareholder1.Country_of_Establishment__c = 'United Arab Emirates';
            shareholderCompanyToInsert.add(shareholder1);
        }         
        Database.insert (shareholderCompanyToInsert,false);
        for(Shareholder_Company__c shareholder: [Select id,Percentage_of_Ownership__c From Shareholder_Company__c WHERE Percentage_of_Ownership__c!= null ]){
            System.AssertEquals(true,shareholder.Percentage_of_Ownership__c<100);
        }
    }
    
}
 
ShirishaShirisha (Salesforce Developers) 
Hi Gaurav,

Greetings!

This error occurs if you are trying to access the Attribute or Object which is null.So,I would suggest you to capture the debug logs while running the test class and you will be able to see the code execution which makes easy to find out the code which is causing the issue.

Once,you find the code or if you suspect that variable is coming as null then add the exception block to catch it.Please find the sample way of using the exception handling in the below doc:

https://help.salesforce.com/articleView?id=000327918&type=1&mode=1

Kindly let me know if it helps you and close your query by marking it as best answer so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Gaurav Shukla 61Gaurav Shukla 61

Hi Shirisha, 

In addition to above query I am getting below error 
///////////Error 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ApplicationTrigger: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.ApplicationTriggerHandler.onBeforeInsert: line 46, column 1
Trigger.ApplicationTrigger: line 7, column 1: [] 

====================================================================================================
Application Trigger 

  1. trigger ApplicationTrigger on Application__c (before insert, after insert,
  2.                                               before update, after update,
  3.                                               before delete, after delete ) {
  4.         /* Before Insert */
  5.         if (Trigger.isInsert && Trigger.isBefore) {
  6.             system.debug('Before insert 1 app triger');
  7.             ApplicationTriggerHandler.onBeforeInsert(Trigger.New);     //Error in this line 
  8.             system.debug('Before insert 2 app triger');
  9.         }
  10.         /* After Insert */
  11.         else if (Trigger.isInsert && Trigger.isAfter) {
  12.             ApplicationTriggerHandler.onAfterInsert(Trigger.New);
  13.             ApplicationTriggerHandler.applicationFirstRun = false;
  14.         }
  15.         /* Before Update */
  16.         else if (Trigger.isUpdate && Trigger.isBefore) {
  17.             if (ApplicationTriggerHandler.applicationFirstRun) {
  18.                 system.debug('Before update 1 app triger');
  19.                 ApplicationTriggerHandler.onBeforeUpdate(Trigger.OldMap, Trigger.NewMap);
  20.                 system.debug('Before update 2 app triger');
  21.             }
  22.         }
  23.         /* After Update */
  24.         else if (Trigger.isUpdate && Trigger.isAfter) {
  25.             if (ApplicationTriggerHandler.applicationFirstRun) {
  26.                 ApplicationTriggerHandler.onAfterUpdate(Trigger.OldMap, Trigger.NewMap);
  27.                /*Added as part of Contacts Fiserv Issue */
  28.                 ApplicationTriggerHelper.UpdateContactsFCRM(Trigger.old);                
  29.             }
  30.             ApplicationTriggerHandler.applicationFirstRun = false;
  31.         }
  32.         /* Before Delete */
  33.         if (Trigger.isDelete && Trigger.isBefore) {
  34.             ApplicationTriggerHandler.onBeforeDelete(Trigger.old);
  35.         }
  36.         /* After Delete */
  37.         else if (Trigger.isDelete && Trigger.isAfter) {
  38.             ApplicationTriggerHandler.onAfterDelete(Trigger.Old);
  39.         }
  40. }

======================================================================================================
ApplicationTriggerHandler
 

  1. public without sharing class ApplicationTriggerHandler {
  2.  
  3.     private static final String mandatoryDescriptionOfBusinessOperations = 'Field must be filled';
  4.     private static final Set<String> VALID_FIELD = new Set<String>{
  5.             '[PassportNumber__c]', '[Birthdate]', '[PassportExpirationDate__c]', '[VisaExpirationDate__c]'
  6.     };
  7.     private static final String CONTACT_HAS_RELATED_OBJECT = 'Contact has related object(s) and can\'t be deleted' ;
  8.     public static final Integer DEFAULT_POS_VALUE = 3500;
  9.     public static final Integer DEFAULT_POS_VALUE_INCL_VAT = 3675;
  10.     private static ID_Generation_Configuration__c idGenerationConfig = ID_Generation_Configuration__c.getOrgDefaults();
  11.     private static Integration_Settings__c intSettings = Integration_Settings__c.getValues(UserInfo.getOrganizationId());
  12.     private static final String DCC_PROVIDER_PLANET_PAYMENT = 'Planet Payment';
  13.     private static final String DCC_PROVIDER_FEXCO = 'FEXCO';
  14.     public static final String DEFAULT_BACKEND_SYSTEM = 'VISION+;BASE24';
  15.     public static final String REJECT_INFO_DIVIDER = '_|_';
  16.     public static Boolean RECALCULATE_FIRST_TIME = false;
  17.  
  18.  
  19.  
  20.     public static Boolean applicationFirstRun = true;
  21.     public static Boolean ownersUpdatedFromCase = false;
  22.  
  23.  
  24.     public class AgreementNumberComparator extends Comparator {
  25.  
  26.         public override Integer compare(Object o1, Object o2) {
  27.             Agreement_Number__c agreementNumber = (Agreement_Number__c) o1;
  28.             Agreement_Number__c agreementNumberToCompare = (Agreement_Number__c) o2;
  29.             return agreementNumber.Name.compareTo(agreementNumberToCompare.Name);
  30.         }
  31.     }
  32.  
  33.     public static void onBeforeInsert(List<Application__c> records) {
  34.         List<Application__c> appForAddContact = new List<Application__c>();
  35.         List<Application__c> appForUpdatePaymentMode = new List<Application__c>();
  36.         Id newRecTypeId = RecordTypeHelper.getIdByDeveloperName(
  37.                 Consts.Application.getDevName(),
  38.                 Consts.Application.RecordTypes.New1
  39.         );
  40.         Id draftRecTypeId = RecordTypeHelper.getIdByDeveloperName(
  41.                 Consts.Application.getDevName(),
  42.                 Consts.Application.RecordTypes.Draft
  43.         );
  44.  
  45.         for (Application__c app : records) {
  46.             if ( intSettings.Skip_Screening_Stage__c ) {       //Error in this line 
  47.                 app.Screening_After_Reject_Required__c = false;
  48.             }
  49.             if (intSettings != null && !intSettings.FCRM_Enabled__c) {
  50.                 app.VL_MerchantCheckedOnMatch__c = Consts.IsTrue.No.getDevName();
  51.             }
  52.             if (ProfileHelper.getProfileToSaleManagerAndOfficer().contains(UserInfo.getProfileId())) {
  53.                 app.SalesRepresentative__c = UserInfo.getUserId();
  54.             }
  55.  
  56.             if (app.RecordTypeId == newRecTypeId) {
  57.                 app.RecordTypeId = draftRecTypeId;
  58.                 appForAddContact.add(app);
  59.             }
==========================================================================================================
Update Test Class 
  1. @IsTest
  2. public class ShareholderCompanyTriggerHandler_Test {
  3.     
  4.     @IsTest
  5.     private static void test_shareholdercompanyPercentage() {
  6.         Consts.Contact_RecordTypes contactRTs = new Consts.Contact_RecordTypes();
  7.         String contactRT = RecordTypeHelper.getIdByDeveloperName('Contact', contactRTs.Acquiring);
  8.         
  9.         //Integration_Settings__c iSetting = Integration_Settings__c.getValues(UserInfo.getOrganizationId()); 
  10.         Application__c application = new Application__c(
  11.             TRN_Legal_Name__c = 'test',
  12.             TaxRegistrationNumberTRN__c = '123456789124111',
  13.             Account_TradeName__c = 'Acme LLC',
  14.             Account_MerchantName__c = 'Test App',
  15.             Account_Email__c = 'testappacmellc@acmellc.com',
  16.             Account_PoBox__c = '123',
  17.             Account_Address__c = '66 13 C St',
  18.             Account_City__c = 'Dubai',
  19.             Account_NumberOfEmployees__c = '1-10',
  20.             GA_Client_ID__c = '35009a79-1a05-49d7-b876-2b884d0f825b',
  21.             GA_Campaign_Id__c = '45029a79-2a07-50d7-b876-2b504d0c321b',
  22.             LeadSource__c = 'Web',
  23.             Contact_FirstName__c = 'TestContact',
  24.             Contact_LastName__c = 'TestContact',
  25.             Contact_MobilePhone__c = '+97-1588051252',
  26.             PassportNumber__c = '12345678qwertyuiop',
  27.             Contact_PassportExpirationDate__c = Date.today() + 100,
  28.             BirthDate__c = Date.today().addYears(-20),
  29.             mpEnvKey__c = 'rock',            
  30.             Account_TotalExpectedCashSales__c = 0,
  31.             Account_TotalExpectedCreditCardSales__c = 5,
  32.             EntityDateOfEstablishment__c = Date.today().addDays(-100),
  33.             EntityCountryOfEstablishment__c = 'United Arab Emirates',
  34.             Account_Phone__c = '980643022681',
  35.             Chargebacks_YTD__c = 1
  36.         );
  37.         //Application__c application = TestUtil.createTestApp();
  38.         if(application!= null ){
  39.             insert application;       //(Error in this line) Class.ShareholderCompanyTriggerHandler_Test.test_shareholdercompanyPercentage: 
  40.         }
  41.         system.debug('Application:::::::::'+application);
  42.         //Creating Contact records
  43.         List<Contact> contactsToInsert = new List<Contact>();
  44.         for(Integer i=0; i<10; i++){
  45.             Contact contact1 = new Contact(
  46.                 accountcontact__c = true,
  47.                 PassportNumber__c = '12345678qwertyuiop',
  48.                 PassportExpirationDate__c = Date.today() + 100,
  49.                 LastName = 'Test1',
  50.                 Nationality__c = 'Indian',
  51.                 MobilePhone = '97121333131',                
  52.                 RecordTypeId = contactRT);            
  53.             Integer randomNumber = Integer.valueof((math.random() * 10));
  54.             if(randomNumber<3)
  55.                 Contact1.PercentageOfOwnership__c = 10;
  56.             else if(randomNumber > 3 && randomNumber <=5)
  57.                 Contact1.PercentageOfOwnership__c = 30;
  58.             else if(randomNumber > 5 && randomNumber <=8)
  59.                 Contact1.PercentageOfOwnership__c = 20;
  60.             else 
  61.                 Contact1.PercentageOfOwnership__c = 130;
  62.             contactsToInsert.add(contact1);            
  63.         }  
  64.         Database.insert (contactsToInsert,false);
  65.         for(Contact contact: [Select id,PercentageOfOwnership__c From Contact WHERE PercentageOfOwnership__c!= null ]){
  66.             system.debug('Percentage:::::::::'+contact.PercentageOfOwnership__c);
  67.             System.AssertEquals(true,contact.PercentageOfOwnership__c<100);
  68.         }
  69.         //Creating Shareholder records
  70.         List<Shareholder_Company__c> shareholderCompanyToInsert = new List<Shareholder_Company__c>();        
  71.         Id ShareHolderComRecordTypeId = RecordTypeHelper.getIdByDeveloperName(Consts.Shareholder.getDevName(), Consts.Shareholder.RecordTypes.Shareholder_Company);
  72.         for(Integer j=0; j<10;j++){
  73.             Shareholder_Company__c shareholder1 = new Shareholder_Company__c();
  74.             shareholder1.RecordTypeId = ShareHolderComRecordTypeId;
  75.             Integer randomNumber = Integer.valueof((math.random() * 10));
  76.             if(randomNumber<3)
  77.                 shareholder1.Percentage_of_Ownership__c = 10;
  78.             else if(randomNumber > 3 && randomNumber <=5)
  79.                 shareholder1.Percentage_of_Ownership__c = 30;
  80.             else if(randomNumber > 5 && randomNumber <=8)
  81.                 shareholder1.Percentage_of_Ownership__c = 20;
  82.             else 
  83.                 shareholder1.Percentage_of_Ownership__c = 130;
  84.             shareholder1.Trade_License_number__c = '4824';
  85.             shareholder1.Name = 'test shareholder company';
  86.             shareholder1.Date_of_Establishment__c = Date.today() - 20;
  87.             shareholder1.Country_of_Establishment__c = 'United Arab Emirates';
  88.             shareholderCompanyToInsert.add(shareholder1);
  89.         }         
  90.         Database.insert (shareholderCompanyToInsert,false);
  91.         for(Shareholder_Company__c shareholder: [Select id,Percentage_of_Ownership__c From Shareholder_Company__c WHERE Percentage_of_Ownership__c!= null ]){
  92.             System.AssertEquals(true,shareholder.Percentage_of_Ownership__c<100);
  93.         }
  94.         List<Shareholder_Company__c> newlist = new List<Shareholder_Company__c>();
  95.         for(Shareholder_Company__c share : shareholderCompanyToInsert){
  96.             share.Trade_License_number__c = '482';
  97.             newlist.add(share);
  98.             
  99.         }
  100.         Database.update (newlist,false);
  101.         //System.AssertEquals(true,newlist.Percentage_of_Ownership__c<100);      
  102.     }
  103.     
  104. }
Please help me I am not sure what is going wrong in this case.
Janet EpebinuJanet Epebinu
Hi Gaurav,
The following are changes you can make to resolve the issues:
For line 46 of the ApplicationTriggerHandler, you should use an operator with the condition. For example, it can be
if ( intSettings.Skip_Screening_Stage__c !=null)  or if (intSettings.Skip_Screening_Stage__c ==null) or something that your object allows

On the error in line 7 of the Trigger, you can try to replace line 7 with the code below
 
List<Application__c> apList  = new List<Application__c>();
        for(Application__c ap : Trigger.New){
         if(condition){ //if there is no condition, delete this
                apList.add(ap);
            }
        }
        if(apList.size() > 0){
   ApplicationTriggerHandler.onBeforeInsert(apList);
   }