[SalesForce] System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

Below error I got while running test class.My test class results fail.Anyone have some idea please share with me.

Error Details :

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, setAccountDetails: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.setAccountDetails: line 3, column 1: []

Stack Trace : Class.XMLparserUpdateTest.testXmlParserUpdate: line 21, column 1

Trigger :

trigger setAccountDetails on Account (before insert, before update) {
        
        Set<String> readOnlyprofiles = new Set<String>(Integration__c.getOrgDefaults().Account_Name_Read_Only_Profiles__c.split(','));
        
        for(Account a : trigger.new) {
            try {
                a.Owner__c = a.OwnerId;
            } catch(Exception e) {}
         
            if( Trigger.isupdate && readOnlyprofiles.contains(UserInfo.getProfileId()) ){
               a.Name = trigger.oldMap.get(a.Id).Name  ;       
            }
        }

Test Class:

@isTest
public class XMLparserUpdateTest {
        
        @isTest
        static void testXmlParserUpdate(){
            
           Account acc = TestDataGenerator.setupAccount(1,false);
           insert acc; // This line we are getting issue 
           }
    }

Generator Class :

@isTest
public class TestDataGenerator {

        public static Account setupAccount(Integer identifier, Boolean insertToDatabase){
            
            Account testAccount = new Account(name = 'Test Account' + identifier); 
                                                    
            if (insertToDatabase) {
                insert testAccount;
            }
            return testAccount;    
        }
    }

Best Answer

You have to create your own test data. This line assumes you can split a string before checking if it is null:

Set<String> readOnlyprofiles = new Set<String>(Integration__c.getOrgDefaults().Account_Name_Read_Only_Profiles__c.split(','));

Instead, you must either add a null check, or have your test actually create this custom setting record.

String names = Integration__c.getOrgDefaults().Account_Name_Read_Only_Profiles__c;
Set<String> readOnlyProfiles = (names == null) ? new Set<String>() : new Set<String>(names.split(',')

Or in your test:

insert new Integration__c(Account_Name_Read_Only_Profiles__c='foo,bar,etc');

Granted, there are probably better ways to check if the running user has a permission. I highly recommend you instead consider using a Custom Permission and then just assigning it to the profiles you would like to whitelist.

if (Trigger.isUpdate && FeatureManagement.checkPermission('IsAccountNameReadOnly'))
Related Topic