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
Harjeet Singh 13Harjeet Singh 13 

How to resolve System.NullPointerException: Attempt to de-reference a null object error in Test Class Salesforce

Dear All,

I have developed a class which is calling standard REST API to determine Daily Apex Exceution Limits. I am getting error when I am running test class for the same.

Below is my Apex Class:
 
public class CurrentStorage{


public static void getStorage() {

//fetch session od of user
String sid = Userinfo.getSessionId();

//fetch Instance URL
String baseURL = System.URL.getSalesforceBaseUrl().toExternalForm();
    
    
//Building call out to Standard Salesforce Rest API
HttpRequest req = new HttpRequest();

req.setMethod('GET');
req.setEndpoint(baseURL+'/services/data/v41.0/limits');
req.setHeader('Authorization', 'OAuth '+ sid);

Http http = new Http();
    
HTTPResponse res = http.send(req);

Map<String, Object> m = (Map<String,Object>)JSON.deserializeUntyped(res.getBody());
Map<String, Object> dataStorage = (Map<String,Object>)m.get('DailyAsyncApexExecutions');
System.debug('Map: '+ dataStorage);
System.debug('Current Storage: ' + dataStorage.get('Remaining'));

If(Integer.valueof(dataStorage.get('Max'))*(0.8)<= (Integer.valueof(dataStorage.get('Max')) - Integer.valueof(dataStorage.get('Remaining')))){
    
    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                message.toAddresses = new String[] { 'abc@gmail.com','def@gmail.com'};
                //message.optOutPolicy = 'FILTER';
                message.subject = 'Async Apex Limits Threshold Warning';
                message.plainTextBody = 'Your Org Limit of Daily Async Apex Execution reached 80% threshold for '+ baseURL;
                Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

			if (results[0].success) 
			{
   				 System.debug('The email was sent successfully.');
			} else 
			{
    				System.debug('The email failed to send: ' + results[0].errors[0].message);
			}
         }
    
 
        
            // Send Mail to people
}

}

Below is my test class:
 
@isTest
public class TestCurrentStorage {
    
    static testMethod void validateLocationCallouts() {
    
         RestRequest req = new RestRequest(); 
        req.params.put('DailyAsyncApexExecutions', '250000');
        //req.params.put('Max', '250000');
        req.params.put('Remaining', '200000');
        
        Test.startTest();
   
    
           Test.setMock(HttpCalloutMock.class, new MockHttpResponse());

           CurrentStorage.getStorage();
          Test.stopTest();
    }
    


}

Below is my mock class:
 
@isTest
global class mockHttpResponse implements HttpCalloutMock{
    
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        System.assertEquals('GET', req.getMethod());
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        
        res.setBody('{"Max": "250000","Remaining": "200000"}');
        res.setStatusCode(200);
        res.setStatus('OK');
        return res;
    }

}

When I am trying to run tess class I am getting below error trace logs:
 
Errors:
System.NullPointerException: Attempt to de-reference a null object


Stack Trace:
Class.CurrentStorage.getStorage:
Class.TestCurrentStorage.validateLocationCallouts:

Kindly help me to pass the test class and also test class showing 57% code coverage and singlemessaging code is not covering

Many thanks in advance

Thanks & Regards,
Harjeet​ ​​