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
Kunal Purohit 4Kunal Purohit 4 

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

Hello Folks, I am getting below error in my apex test class.
System.NullPointerException: Attempt to de-reference a null object
Here is my controller and its test class.
public class SendEligibilityFileDetailsToProductCtrl {
    
    public SendEligibilityFileDetailsToProductCtrl(ApexPages.StandardController stdController) {
        
    }
    
    public PageReference SendEligibilityFileDetailsToProduct(){
        String eligibilityFileId = ApexPages.currentPage().getParameters().get('id');
        String environmentCode = 'bst';
        
        Eligibility_File__c eligibilityFile = [Select Id, Name, Eligibility_File_Name__c, Product_Response__c,ProgramList__c from Eligibility_File__c Where Id = :eligibilityFileId Limit 1];
        System.debug('Eligibility-->:' +eligibilityFile);
        string eligibilityFileAPIDetails = Utility.getServiceURLFromEnvironmentSettings(environmentCode) + 'EligibilityFile';
        String tokenHeader = Utility.getTokenFromEnvironmentSettings(environmentCode);
        EligibilityFileDTO eligibilityFileDTO = new EligibilityFileDTO();
        eligibilityFileDTO.FileName = eligibilityFile.Eligibility_File_Name__c;
        eligibilityFileDTO.Version = eligibilityFile.Name;
      
        
         // Custom Setting 
       EligiblityFileProductDetails__c CustomSetting = EligiblityFileProductDetails__c.getvalues(eligibilityFile.ProgramList__c);   
        System.debug('CustomSetting -->>'+CustomSetting);
        
        if(eligibilityFile.ProgramList__c != Null ){
            System.debug(eligibilityFile.ProgramList__c);
         
          eligibilityFileDTO.ProgramList = CustomSetting.ProgramList__c;         
           System.debug(eligibilityFileDTO.ProgramList);
                  
        }    
         
          System.debug('Value of eligibilityFileDTO:'+eligibilityFileDTO) ;
         
        System.debug('Endpoint: ' + eligibilityFileAPIDetails);
        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Length', '0');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Authorization', tokenHeader);
        req.setEndpoint(eligibilityFileAPIDetails);
        req.setMethod('POST');
        String requestBody = JSON.serialize(eligibilityFileDTO).replace('\\','').replace('"[{','[{').replace('}]"','}]');
       
        System.debug('requestBody >>> ' + requestBody);
        req.setBody(requestBody);
        
        Http http = new Http();
        req.setTimeout(120000);
        try{   
            String jsonstr = '';
            HTTPResponse respns = http.send(req);
            if (respns.getStatusCode() != null && respns.getStatusCode() == 401) {
                System.debug('Error Occured>>>');
                tokenHeader = Utility.getToken(environmentCode);
                req.setHeader('Authorization', tokenHeader);
                respns = http.send(req);
                System.debug('Response >>> '+ respns );
                jsonstr = respns.getBody();
                Utility.updateTokenForEnvironmentSettings(environmentCode, tokenHeader);
            }else{
                jsonstr= respns.getBody();      
            }
            System.debug('Response >>> ' + jsonstr);
            
            //hcpDetails = (HCPDetails)JSON.deserialize(jsonstr, HCPDetails.class);
            //System.debug(hcpDetails);
            
            eligibilityFile.Product_Response__c = jsonstr;
        }catch (System.NullPointerException e){
            System.debug('The following exception has occurred: ' + e.getMessage());
            //message = 'The following exception has occurred: ' + e.getMessage();
            eligibilityFile.Product_Response__c = e.getMessage();
        }
        
        update eligibilityFile;
        
        PageReference pr = new PageReference('/' + eligibilityFileId);
        pr.setredirect(true);
        return pr;
    }
        
    public class EligibilityFileDTO{
        public String FileName {get;set;}
        public String Version {get;set;}
        public String ProgramList {get;set;}
        
    }
    
}


Test Class

@isTest
private class SendEligibilityFileDetailsTest{
    
    @isTest
    static void testSendEligibilityFileDetailsToProduct() {
        // Create test data
        Eligibility_File__c eligibilityFile = new Eligibility_File__c(
            
            Eligibility_File_Name__c = 'Test Eligibility File Name',
            ProgramList__c = 'Only DeRx'
        );

        insert eligibilityFile;
        
        String environmentCode = 'adapt';
        String tokenHeader = 'fakeTokenHeader';
        String serviceURL = 'https://test.service.com/';
        
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
  
        Utility.getEnvironmentCode(environmentCode);
        Utility.getTokenFromEnvironmentSettings(tokenHeader);
        Utility.getServiceURLFromEnvironmentSettings(serviceURL);        
        ApexPages.currentPage().getParameters().put('id', eligibilityFile.Id);
        
        // Set up mock HTTP response
        HttpResponse mockResponse = new HttpResponse();
        mockResponse.setStatusCode(200);
        mockResponse.setBody('{}');
        
        // Set up mock HTTP callout
   //     Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator(mockResponse));
        
        // Create controller and call method under test
        ApexPages.StandardController stdController = new ApexPages.StandardController(eligibilityFile);
        SendEligibilityFileDetailsToProductCtrl controller = new SendEligibilityFileDetailsToProductCtrl(stdController);
        controller.SendEligibilityFileDetailsToProduct();
        
        SendEligibilityFileDetailsToProductCtrl.EligibilityFileDTO first = new  SendEligibilityFileDetailsToProductCtrl.EligibilityFileDTO();
        first.ProgramList='Only DeRx';
        
        EligiblityFileProductDetails__c custsetting = new EligiblityFileProductDetails__c();
        custsetting.ProgramList__c = first.ProgramList;
        
        // Verify that the eligibility file was updated
        eligibilityFile = [SELECT Product_Response__c FROM Eligibility_File__c WHERE Id = :eligibilityFile.Id];
        System.assertEquals('{}', eligibilityFile.Product_Response__c);
    }
    
    
        // Mock HttpResponseGenerator class for HTTP callouts
    private class MockHttpResponseGenerator implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            HTTPResponse res = new HTTPResponse();
           
            res.setStatusCode(200);
            res.setBody('{"result": "success"}');
            return res;
        }
    }
    
    @isTest
	static void testMyHttpRequest() {
    // Set up mock response
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());

    // Create HttpRequest and set headers
    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Length', '0');
    req.setHeader('Content-Type', 'application/json');
    req.setHeader('Authorization', 'myToken');
    req.setEndpoint('https://myendpoint.com');
    req.setMethod('POST');

    // Create request body
    String requestBody = '{"name": "John"}';
    req.setBody(requestBody);

    // Send HTTP request
    Http http = new Http();
    HTTPResponse res = http.send(req);

    // Verify response
    System.assertEquals(200, res.getStatusCode());
    System.assertEquals('{"result": "success"}', res.getBody());
}

}
SwethaSwetha (Salesforce Developers) 
HI Kunal,

In the SendEligibilityFileDetailsToProduct() method, you are querying the Eligibility_File__c object and storing it in the eligibilityFile variable. If there are no records that match the query, eligibilityFile will be null, and you will get a null pointer exception when you try to access its properties. To avoid this, you should check that the query returned a record before accessing its properties:
 
Eligibility_File__c eligibilityFile = [SELECT Id, Name, Eligibility_File_Name__c, Product_Response__c, ProgramList__c FROM Eligibility_File__c WHERE Id = :eligibilityFileId LIMIT 1];
if (eligibilityFile != null) {
    // access eligibilityFile properties here
} else {
    // handle the case where no record was found
}

In the test class, you are setting the ApexPages.currentPage().getParameters().put('id', eligibilityFile.Id); to set the ID of the eligibility file. However, if the eligibilityFile variable is null, this line will cause a null pointer exception. To avoid this, you should only set the parameter if eligibilityFile is not null:
if (eligibilityFile != null) {
    ApexPages.currentPage().getParameters().put('id', eligibilityFile.Id);
}

If this information helps, please mark the answer as best. Thank you