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
Sana123Sana123 

I am getting this error during my test class

I am getting this error----
System.DmlException: Delete failed. First exception on row 0 with id 0015g00000N5pRcAAJ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger1: execution of AfterDelete

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

Class.AccountTriggerHandler1.createContactsv1: line 124, column 1
Trigger.AccountTrigger1: line 21, column 1: []



this is my trigger ---
@isTest
public class AccountTriggerHandlerTest {
    @isTest
    public static void createContactsv2Test()
    {
        List<Account> listOfaccounts = new List<Account>();
        
        String str = 'FirstName=Anjana,LastName=Sharma,MobilePhone=32342342,Email=anjana@gmail.com';
        String str2 = 'FirstName=Anjana,LastName=Sharma,MobilePhone=32342342,Email=anjana@gmail.com'+'\r\n'
            +'FirstName=Bob23,LastName=Bob23,MobilePhone=322222,Email=bb212@gmail.com';
        
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.Contacts__c='FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com'+'\r\n'
            +'FirstName=B,LastName=B,MobilePhone=2,Email=bb@unknown.com';
        listOfaccounts.add(acc);
 
        Account acc1 = new Account();
        acc1.Name = 'Test12';
        acc1.Contacts__c = str;
        acc1.Move_To_Contacts__c = 'FirstName=Anjanakk,LastName=Sharmakk,MobilePhone=323242342,Email=anjana11@gmail.com';
        listOfaccounts.add(acc1);
        
        Account acc2 = new Account();
        acc2.Name = 'Testing';
        acc2.Contacts__c = str2;
        acc2.Move_To_Contacts__c = 'FirstName=Anjana,LastName=Sharma,MobilePhone=32342342,Email=anjana@gmail.com';
        listOfaccounts.add(acc2);
        
        Account lookUpAccount = new Account(Name = 'LookUp');
        insert lookUpAccount;
        
        listOfaccounts[1].Move_To_Account__c = lookUpAccount.Id;
        listOfaccounts[2].Move_To_Account__c = lookUpAccount.Id;
        
        insert listOfaccounts;
        
        system.debug('listOfaccounts'+ listOfaccounts);
        
        
        //insert con;

        List<Contact> insertedContacts = [SELECT Id, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :listOfaccounts] ;
        
        Contact con = new Contact();
        con.LastName = 'Test Contact';
        con.AccountId = acc.Id;
        con.email='abc@gmail.com';
        insertedContacts.add(con);
        system.debug('insertedContacts'+ insertedContacts);
        
                
        //acc.Name='Test';
        //
        listOfaccounts[0].Contacts__c = '';
            //System.debug('accounts[0].Contacts__c: ' + accounts[0].Contacts__c);
        
       String st = 'FirstName=an,LastName=Sh,MobilePhone=32342,Email=anjana541@gmail.com';
       String str1 = 'FirstName=Anjana1,LastName=Sharma1,MobilePhone=323424342,Email=anjana1@gmail.com'+'\r\n'
            +'FirstName=Bob,LastName=Bob,MobilePhone=3222,Email=bb12@gmail.com';   
        
         listOfaccounts[1].Contacts__c=st;
         listOfaccounts[1].Move_To_Contacts__c ='FirstName=Bob1,LastName=Bob3,MobilePhone=32232,Email=bb312@gmail.com';
     
         listOfaccounts[2].Contacts__c=str1;
         listOfaccounts[2].Move_To_Contacts__c ='FirstName=Anjana1,LastName=Sharma1,MobilePhone=323424342,Email=anjana1@gmail.com'+'\r\n'
            +'FirstName=Bob,LastName=Bob,MobilePhone=3222,Email=bb12@gmail.com';
              
        update listOfaccounts;
        
        system.debug('listOfaccounts'+ listOfaccounts);
        
        system.assertEquals(listOfaccounts[2].Contacts__c,listOfaccounts[2].Move_To_Contacts__c);
        
        /*String st = 'FirstName=an,LastName=Sh,MobilePhone=32342,Email=anjana541@gmail.com';
           
         acc2.Contacts__c=st;
         acc2.Move_To_Contacts__c ='FirstName=Bob1,LastName=Bob3,MobilePhone=32232,Email=bb312@gmail.com';*/
        
         //  acc1.Move_To_Contacts__c ='FirstName=Anjana1,LastName=Sharma1,MobilePhone=323424342,Email=anjana1@gmail.com';
           
        //update listOfaccounts;
        //delete listOfaccounts;
        //system.assertEquals(listOfaccounts, null);
        //
        List<Contact> totalContacts = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :listOfaccounts[1].Id];
        System.assertEquals(1 , totalContacts.size());
        
        List<Contact> listOfContactDeleted = [SELECT AccountId, FirstName ,LastName , MobilePhone,email FROM Contact WHERE AccountId = :listOfaccounts[0].Id];
        //System.debug('listOfContactDeleted: '+ listOfContactDeleted.size());
        System.assertEquals(0 , listOfContactDeleted.size());
        
      delete listOfaccounts[2];
        
    }
        }


this is my handler----

public static void createContactsv2 (List<Account>listAccounts, Map<Id, Account>mapOfoldAccount){
        
        Set<Id> accountIds = new Set<Id>();
        Set<String> contactEmailStringSet = new  Set<String>();
        Set<Account> accIDs = new Set<Account>();
 
        for (Account acc: listAccounts){
            accIDs.add(acc);
        }
    
        List<Contact> listOfdeletContact = [SELECT AccountId FROM Contact WHERE AccountId IN : accIDs];
        if(listOfdeletContact.Size()>0){
           delete listOfdeletContact;

        }
        
        for(Account account : listAccounts){
            system.debug(mapOfoldAccount);
            if(mapOfoldAccount!= null && (String.isNotBlank(account.Contacts__c) && mapOfoldAccount.get(account.Id).Contacts__c != account.Contacts__c))
            {
                
                List<String> listOfContacts = account.Contacts__c.split('\n');
                Set<String> setOfConatcts = new Set<String>(listOfContacts ) ;
                
                for(String lisofstr  : setOfConatcts){
                    System.debug('contactToBeUpsert');
                    
                    accountIds.add(account.Id);
                    contactEmailStringSet.add(lisofstr.substringAfter('Email=').substringBefore(',').replaceAll('\\s', ''));
                    
                }
            }
        }
        
        Map<String, Contact> mapOfContacts = new Map<String, Contact>();
        System.debug(contactEmailStringSet);
        if(contactEmailStringSet.size()>0)
        {     
            for(Contact contact :  [Select id, FirstName, LastName, Email, MobilePhone FROM Contact WHERE AccountId IN :accountIds AND Email IN :contactEmailStringSet]){  
                System.debug(contact);
                mapOfContacts.put(contact.Email, contact);
                
            }
            
        }
         
        List<Contact> contactToBeUpsert = new List<Contact>();
        
        for(Account account : listAccounts)
        {
            if(String.isNotBlank(account.Contacts__c))
            {
                List<String> listOfContactString = account.Contacts__c.split('\n');
                for(String lstString : listOfContactString)
                {  
                    String email = lstString.substringAfter('Email=').substringBefore(',').replaceAll('\\s', '');
                    System.debug(email);
                    if(mapOfContacts.containsKey(email))
                    {
                        contactToBeUpsert.add(new Contact(Id = mapOfContacts.get(email).Id,
                                                          FirstName = lstString.substringAfter('FirstName=').substringBefore(','), 
                                                          LastName = lstString.substringAfter('LastName=').substringBefore(','),
                                                          MobilePhone =lstString.substringAfter('MobilePhone=').substringBefore(',')));
                        System.debug('contactToBeUpsert');  
                    }
                    else
                    {
                        contactToBeUpsert.add(new Contact(FirstName = lstString.substringAfter('FirstName=').substringBefore(','), 
                                                          LastName = lstString.substringAfter('LastName=').substringBefore(','),
                                                          Email = lstString.substringAfter('Email=').substringBefore(','),
                                                          MobilePhone =lstString.substringAfter('MobilePhone=').substringBefore(','),
                                                          AccountId = account.Id));
                        
                        System.debug('contactToBeUpsert');    
                    }  
                }
            }      
        }
     
        System.debug(contactToBeUpsert);
    
            if(contactToBeUpsert.Size()>0){
            upsert contactToBeUpsert;
        }
    /* for(Account account : listAccounts){
        if(account.Contacts__c != mapOfoldAccount.get(account.ID).Contacts__c && account.Contacts__c.split('\n').size() < 
           mapOfoldAccount.get(account.ID).Contacts__c.split('\n').size()){
               for(Contact con : [Select id, FirstName, LastName, Email, MobilePhone FROM Contact WHERE AccountId IN :accountIds]){
                   if(!account.Contacts__c.contains(con.FirstName)){
                       listOfdeleteContact.add(con);
                   }
                   
               }
           }
    }*/
        
    }
    
    
public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    Set<Id> setOfIds = new Set<Id>();
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
   
    List<Account> accountToUpdate = new List<Account>();
    for(Account account : listOfAccounts){
        
        if(String.isNotBlank(account.Move_To_Account__c) && String.isNotBlank(account.Move_To_Contacts__c) && (mapoldAccount == null 
                                               || mapoldAccount.get(account.Id).Move_To_Account__c != account.Move_To_Account__c
                                               || mapoldAccount.get(account.Id).Move_To_Contacts__c != account.Move_To_Contacts__c))
            
        {
             
             List<String> listOfContacts = account.Contacts__c.split('\n');
             List<String> listOfMoveToContacts = account.Move_To_Contacts__c.split('\n');
            
            
            if(listOfContacts.size()>0)
            {
                String moveToContact = '';
                for(String contact : listOfMoveToContacts)
                {
                    if(listOfMoveToContacts.size()>0 && listOfContacts.contains(contact))  {
                        
                        if(!mapOfAccountIdAndString.containsKey(account.Move_To_Account__c)) //false
                            mapOfAccountIdAndString.put(account.Move_To_Account__c, new List<String>());
                        
                        mapOfAccountIdAndString.get(account.Move_To_Account__c).add(contact); //st/ st2 //st3
                        setOfIds.add(account.Id);
                        moveToContact = '\n';//if move to contact value is contains in contact__c value 
                    }
                    else{
                         moveToContact = moveToContact+contact+'\n'; //if not contains then add contact to movettocontact
                    }
                   
                }
                moveToContact = String.isNotBlank(moveToContact)?moveToContact:moveToContact.replaceAll('\\s', '');
                accountToUpdate.add(new Account(Id = account.Id, Move_To_Contacts__c = moveToContact));
            }
            
        }
    }
    
    if(mapOfAccountIdAndString.size() > 0)
    {    
        for(Id accountId : mapOfAccountIdAndString.keySet()) 
        {
            String contactValue = '';
            for(String contact : mapOfAccountIdAndString.get(accountId))
            {
                contactValue = contactValue+contact+'\n';
            }
            accountToUpdate.add(new Account(Id = accountId, Contacts__c = contactValue));
        }
        
        if(accountToUpdate.size()>0) update accountToUpdate; 
    }
    
    if(setOfIds.size()>0)
    {
        
        List<Contact> contacts = [SELECT Id, Email, FirstName, LastName, Account.Move_To_Account__c, AccountId FROM Contact WHERE AccountId  IN :setOfIds];
        
        list<Contact> contactsTomoved = new List<Contact>();
        if(contacts.size()>0)
        {
            for(Contact contact : contacts)
            {
                for(String contString : mapOfAccountIdAndString.get(contact.Account.Move_To_Account__c))
                { 
                    
                    if(contact.FirstName == contString.substringAfter('FirstName=').substringBefore(',')
                       && contact.LastName == contString.substringAfter('LastName=').substringBefore(',')
                       && contact.Email == contString.substringAfter('Email=').substringBefore(','))
                    {
                        contact.AccountId = contact.Account.Move_To_Account__c;
                        contactsTomoved.add(contact);
                    }
                }
                
            }
        }
        
        if(contactsTomoved.size() > 0) update contactsTomoved;  
    }
 }
}


this is my trigger --

trigger AccountTrigger1 on Account (after insert , after update , after delete ) {
if(trigger.isAfter &&(Trigger.isInsert || Trigger.isUpdate)){
        AccountTriggerHandler1.createContactsv2(trigger.new, trigger.oldMap);
        AccountTriggerHandler1.createContactsv1(trigger.new, trigger.oldMap);
    }
    if(trigger.isAfter &&Trigger.isDelete){
        AccountTriggerHandler1.createContactsv1(null , trigger.oldMap);
        AccountTriggerHandler1.createContactsv2(null, trigger.oldMap);
        
    }
}
AnkaiahAnkaiah (Salesforce Developers) 
Hi Sana,

Please check the null condition before iteratting the records.
the below method listOfAccounts variable have null values.

public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    Set<Id> setOfIds = new Set<Id>();
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
   
    List<Account> accountToUpdate = new List<Account>();
//my code
if (listOfAccounts.size()>0){
    for(Account account : listOfAccounts){

Please check Null conditions for all loops and issue will resolve.

If this helps, please mark it as best answer

Thank you!!