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
AljebouriAljebouri 

error when running test class System.NullPointerException: Attempt to de-reference a null object

i wrote a test class to test a trigger and future apex class, nevertheless i am reciving this error message, can anyone help me out

System.DmlException: Update failed. First exception on row 0 with id 00Q260000034xE0EAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CP_Approve_Rejects: execution of AfterUpdate

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

Trigger.CP_Approve_Rejects: line 9, column 1: []


Test class code as below
@isTest
private class CP_Approve_Reject_Test {
    static testmethod void  Approve_CP_Lead() {              
        // This causes a fake response to be generated
         Lead lead = new Lead(firstName='first', lastName='last', company='company', leadSource='Client-Portal-Lead-Cn', entity__c='Hong Kong', isTest__c=true);
      
        
              
              
        Test.startTest();
         insert lead;
          Lead leads = lead;
         leads.Approval_Status__c ='Approved';
         update(leads);
        Test.setMock(WebServiceMock.class, new ADSSWebServicesMockImpl());
         
        // Test.setMock(WebServiceMock.class, new ADSSWebServicesMockImpl());
        
        Test.stopTest();

    }
    
    }
Best Answer chosen by Aljebouri
Lalit Mistry 21Lalit Mistry 21
Simply delete the line 3 in your trigger code i.e. remove leadIds = null;
 

All Answers

Lalit Mistry 21Lalit Mistry 21
You'll need to paste trigger CP_Approve_Rejects code to get it resolved for you.
AljebouriAljebouri
as per your request, kindly find trigger code
CP_Approve_Rejects
trigger CP_Approve_Rejects on Lead (after update) {
Set<Id> leadIds = new Set<Id>();
leadIds= null;
    Integer i=0;
          for(Lead ld :  trigger.new) {
           // Lead newLead = (Lead)so;
             //Lead oldLead = (Lead)oldRecords.get(newLead.Id);             
            if (ld.Approval_Status__c =='Approved' && ld.LeadSource == 'Client-Portal-Lead-Cn' && ld.entity__c=='Hong Kong' && Trigger.old[i].Approval_Status__c !='Approved')
             leadIds.add(ld.Id);
               i++;
            }
           
          if (leadIds !=null)  
          leadCPApprovals.Approve_CPLEads(leadIds);
}


Future class leadCPApprvoals
public class leadCPApprovals{

  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void Approve_CPLEads(Set<Id> leadID) {
    for (lead ld: [select id, email from lead where id in:leadID])
    {
       System.debug('--> ConvertIBPortal_Lead Debuging');
       //IBPortalWS_LeadConvert.Convert_LeadPort stub= new  IBPortalWS_LeadConvert.Convert_LeadPort();        
       //String output = stub.Lead_Converted(Integer.Valueof(ld.IBPortalID__c),ld.SF_LeadID__c);
        ClientPortal_lead.Lead_Approval(ld.email);
       //System.debug('--> ConvertIBPortal_Lead'+output);
       //ld.Is_IBPortal_Update__c=false;
       //update(ld);
    }
  }
}
Lalit Mistry 21Lalit Mistry 21
Simply delete the line 3 in your trigger code i.e. remove leadIds = null;
 
This was selected as the best answer
AljebouriAljebouri
worked, thank you so much
 
deepa deshpande 15deepa deshpande 15
Hi Team,

Can you please help me with the below error.
System.NullPointerException: Attempt to de-reference a null object
Class.CtrlCallReport.validtocreate: line 1939, column 1
Class.CtrlCallReport.<init>: line 249, column 1
Class.CtrlCallReport_Test.UpdateNotValidtoCreate: line 559, column 1

Highted lines are the number where iam getting the error.

apex class****

  public Boolean validtocreate(){
        boolean haserror = false;
        system.debug('@@-validtocreate:' + userinfo.getDefaultCurrency());
        
        Map<String, Integer> daymap = new Map<String, Integer>();
        List<String> tempCallDate = new List<String>();
        Map<String, Integer> daymapWeekends = new Map<String, Integer>();
        //To verify current logged in user as VN and calculates current months call report
        String dateto = String.ValueOf(date.valueOf(System.Today().addDays(-1)));
        Date dueDate=date.valueOf(dateto);
        system.debug('--Due days---:'+dueDate);
        system.debug('--Date Rep---:'+dateRep);
        integer numberDaysDue=0;
        Integer daysbefore=0;
        String datefrom =null;
        if(u.DefaultCurrencyIsoCode==defalutCurrency && dateRep!=null){
            //numberDaysDue = -1 * dateRep.daysBetween(dueDate);
            //numberDaysDue=-1 * Integer.valueOf(Days_Validation__c.getInstance(UserInfo.getDefaultCurrency()).Call_Report_Days__c);
            numberDaysDue=-30;
            system.debug('numberDaysDue'+numberDaysDue);
            datefrom=String.ValueOf(Date.valueOf(system.today().addDays(numberDaysDue)));
            system.debug('IF@@@@@@:'+datefrom);
            for(Integer x = numberDaysDue ; x < 0; x++){
                    tempCallDate.add(string.valueOf(Date.valueOf(system.today().addDays(x))));
                    Date dt = Date.valueOf(system.today().addDays(x));
                    if(dt > dateRep){
                        system.debug('@@-:IF--------:tempCallDate:'+tempCallDate);
                        system.debug('--Date Rep---:'+dateRep);
                        system.debug('Dates:::'+dt);
                        daymap.put(string.valueOf(Date.valueOf(system.today().addDays(x))), 0);
                        system.debug('@@-:IF--------:Daymap::'+daymap);
                    }
                    
            }
            system.debug('@@-:IF--------:Daymap::'+daymap.size());
        } 
            
       else{
            daysbefore = -1 * Integer.valueOf(Days_Validation__c.getInstance(UserInfo.getDefaultCurrency()).Call_Report_Days__c);
            System.debug('@@-daysbefore:'+daysbefore);
            datefrom=String.ValueOf(Date.valueOf(system.today().addDays(daysbefore)));
            system.debug('@@@@@@ELSE:'+datefrom);
            for(Integer x = daysbefore ; x < 0; x++){
                daymap.put(string.valueOf(Date.valueOf(system.today().addDays(x))), 0);
                system.debug('@@-:else--------:Daymap::'+daymap);
                tempCallDate.add(string.valueOf(Date.valueOf(system.today().addDays(x))));
                system.debug('@@-Else-----tempCallDate:'+tempCallDate);
            }
        
        }

Testclass ****

    static testmethod void ValidtoCreate(){
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                    EmailEncodingKey='UTF-8', LastName='Enrolment_User', LanguageLocaleKey='en_US', 
                    LocaleSidKey='en_US', ProfileId = p.Id, Business_Unit__c = 'CARDIO', CurrencyIsoCode = 'EUR',
                    Custom_Object_Country__c = 'Morocco', ATC_Class__c = 'C5C C10A C10B C4A C9A C9C C2A C1E C8A', 
                    DefaultCurrencyIsoCode = 'EUR', Weekend_1__c = 'Saturday', Weekend_2__c = 'Sunday',
                    TimeZoneSidKey='America/Los_Angeles', UserName='traingdump@testorg.com');
        
        Days_Validation__c dvc = new Days_Validation__c(name = 'tsetasf',
                                                        isDeleted = false,
                                                        CurrencyIsoCode = 'EUR',
                                                        Call_Report_Days__c = 20,
                                                        SetupOwnerId = u.Id
                                                        );
        Insert dvc;

        System.runAs(u) {  

            Marketing_Cycle__c MC = createMarketingCycle('CARDIO');

            Target__c target = createTarget(u);
            
            List<Pharma_Product__c> ppList = new List<Pharma_Product__c>();
            for(integer x = 0; x < 4; x++){
                Pharma_Product__c pp = new Pharma_Product__c();
                pp.Name = 'test ' + x;
                pp.Local_Type__c = 'Global';
                pp.Product_Type__c = 'Product';
                pp.Country__c = 'Morocco';
                pp.CurrencyIsoCode = 'EUR';
                pp.ATC_Class__c = 'C5C';
                pp.Status__c = 'Active';
                ppList.add(pp);
            }
            insert ppList;


            Call_Report__c callrep = new Call_Report__c();
            callrep.Organisation__c = org.Id;
            callrep.Contact1__c = cust.Id;
            callrep.Date_Time__c  = datetime.now();
            Callrep.Date__c = System.today().addDays(-5);
            callrep.User__c = u.Id; //UserInfo.getUserId();
            callrep.Duration__c = '30';
            callrep.Type__c = '1:1';
            callrep.Next_Call_Objective__c = 'Next Objective TEST';
            callrep.Prio_1_Product__c = ppList[0].id;
            callrep.Prio_2_Product__c = ppList[1].id;
            callrep.Prio_3_Product__c = ppList[2].id;
            callrep.Prio_4_Product__c = ppList[3].id;
            callrep.Prio_1_Marketing_Message_1__c =  ppmList[0].name; 
            callrep.Prio_1_Marketing_Message_2__c =  ppmList[1].name;
            callrep.Prio_1_Marketing_Message_3__c =  ppmList[2].name; 
            callrep.Prio_2_Marketing_Message_1__c =  ppmList[3].name; 
            callrep.Prio_2_Marketing_Message_2__c =  ppmList[4].name; 
            callrep.Prio_2_Marketing_Message_3__c =  ppmList[5].name; 
            callrep.Prio_3_Marketing_Message_1__c =  ppmList[6].name; 
            callrep.Prio_3_Marketing_Message_2__c =  ppmList[7].name; 
            callrep.Prio_3_Marketing_Message_3__c =  ppmList[8].name; 
            callrep.Prio_4_Marketing_Message_1__c =  ppmList[9].name; 
            callrep.Prio_4_Marketing_Message_2__c =  ppmList[10].name; 
            callrep.Prio_4_Marketing_Message_3__c =  ppmList[11].name; 
            callrep.Prio_1_Planned_Objectives__c = pocList[0].Name;
            callrep.Prio_2_Planned_Objectives__c = pocList[1].Name;
            callrep.Prio_3_Planned_Objectives__c = pocList[2].Name;
            callrep.Prio_4_Planned_Objectives__c = pocList[3].Name;
            callrep.Prio_1_Key_Messages__c = KeyMeslist[0].Name;
            callrep.Prio_2_Key_Messages__c = KeyMeslist[1].Name;
            callrep.Prio_3_Key_Messages__c = KeyMeslist[2].Name;
            callrep.Prio_4_Key_Messages__c = KeyMeslist[3].Name;
            callrep.Next_appointment_date__c = system.today().addDays(5);
            callrep.ownerId=u.Id;
            Insert callrep;

            Time_off_Territory__c tot = new Time_off_Territory__c(Start_Date__c = system.today().addDays(-2),
                                                            End_Date__c = system.today().addDays(-1),
                                                            All_Day__c = True,
                                                            Type__c = 'Closed',
                                                            Type_First_Quarter__c='Test1'
                                                            );
            insert tot;


            Event_Attendee__c eventAttendee = new Event_Attendee__c(Pharma_Event__c = evt.Id, Attendee__c = cust.Id, CurrencyIsoCode = 'EUR');
            insert eventAttendee;

            //first test (insert)
            PageReference pageRefInsert = new PageReference('/apex/Product_Pre_Population');
            Test.setCurrentPage(pageRefInsert);
            ApexPages.currentPage().getParameters().put('con', callrep.Contact1__c);
            ApexPages.currentPage().getParameters().put('org', callrep.Organisation__c);
            ApexPages.currentPage().getParameters().put('plan1', callrep.Prio_1_Planned_Objectives__c);
            ApexPages.currentPage().getParameters().put('plan2', callrep.Prio_2_Planned_Objectives__c);
            ApexPages.currentPage().getParameters().put('plan3', callrep.Prio_3_Planned_Objectives__c);
            ApexPages.currentPage().getParameters().put('plan4', callrep.Prio_4_Planned_Objectives__c);
                
            // Open Custom Controller
            ApexPages.StandardController ExtControllerInsert = new ApexPages.StandardController(callrep);
                        
            // Open extension
            CtrlCallReport cr = new CtrlCallReport(ExtControllerInsert);

            Test.startTest();
                        
         
    }