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
shruthikashruthika 

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

Hi all,

 

I am getting an error while writing test class on merging trigger 

 

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

 

This is the error am getting please give me the solution as soon as possible.

 

Below is the code which i have written.....

 

@isTest
private class MQL
{
    static testMethod void myUnitTest()
    {
          Date t = date.today();
          Date d = Date.newInstance(t.year(),t.month(),t.day());
   
        //  Query the StageName
       
        Opportunity opp = [Select StageName, MQL_Promotion_Date__c, MQL_Rejection_Date__c from Opportunity WHERE Name = 'MQL'];
       
        System.Debug(' Val '+opp.StageName);
        System.Debug('Opp MQl Date Val '+string.valueof(opp.MQL_Promotion_Date__c));
      
        if(opp.StageName=='Lead' || opp.StageName=='Qualified Lead')
        {
            opp.StageName = 'D - Qualify';
            update opp;
           
            if(opp.StageName != 'Lead' && opp.StageName != 'Qualified Lead' && opp.StageName != 'No Opportunity')
            {        
                //System.assertEquals(opp.MQL_Promotion_Date__c,d);         
                System.debug('*** Oppty changed from Lead to something other than Lead or No Opportunity - date set to ' + System.today()+' ****');
      //  date MQLd=opp.MQL_Promotion_Date__c;
      //  MQLd=date.today();
          //  boolean dueNow = d.isSameDa(opp.MQL_Promotion_Date__c);
            system.debug(opp.MQL_Promotion_Date__c.isSameDay(d));
            }
            if(opp.StageName == 'No Opportunity')
            {
                //System.assertEquals(opp.MQL_Promotion_Date__c,d); 
                System.debug('*** Oppty changed from Lead to No Opportunity-date set to'+System.today() +'****');
                system.debug(opp.MQL_Rejection_Date__c.isSameDay(d));
            }
       }
    }
}



Thanks in advance.....

shruthika...





rohitsfdcrohitsfdc

hi,

initialize opp object before using it. and make sure the query is returning something before using the instance.

Opportunity opp=new Opportunity ();

Vivek Kumar - IBMVivek Kumar - IBM

Hi Shruthika,

 

In test method it's better to create test data so that it can not be dependent on any org's data.

This error is just because you are quering opportunity record that may not exist in the org now.