‘System.NullPointerException: Attempt to de-reference a null object’ error on test class for @RestResource @HttpPost

apexhttppostpost

I developed an Apex REST web service in Salesforce with the method 'POST'
This is my main class

public class Product {
    public String pName;
    public String pRating;
    public List<Item> Items;
}

public class Item{
    public String Name;
    public String Code;
}
@HttpPost
global static String createRecord() {
    
    RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String jSONRequestBody=req.requestBody.toString();
        Map<String,Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(jSONRequestBody);
        String root = JSON.serialize(jsonMap.get('Product'));
        List<Product> Products = (List<Product>)JSON.deserialize(root,Product[].class);
    // Other logic for inserting records in objects
}

I am trying to write a test class for this, when i run the test class i am getting this error 'System.NullPointerException: Attempt to de-reference a null object'
Here is the test class

    @istest
    public static void dataSetup(){
        
        String ProductJson = '{'+
        '    \"Product\": [{'+
        '        \"pName\": \"Name new patch\", '+
        '        \"pRating\": \"15\", '+
        '    \"Item\":[                                 '+
        '         {                      '+
        '        \"Name\": \"item1\" ,'+
        '        \"Code\" : \"54294\" '+
        '        },'+
        '        {'+
        '        \"Name\": \"item2\",'+
        '        \"Code\" : \"57435\"'+
        '        }'+
        '     ],'+
        '    }]'+
        '}';
    
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        req.requestURI = '/services/apexrest/demoURL';
        req.httpMethod = 'POST';
        req.requestBody = Blob.valueOf(ProductJson);
        RestContext.request = req;
        RestContext.response = res;

        Test.startTest();
        myRESTAPI.createRecord();
        Test.stopTest();
}

Best Answer

The error is related to the fact that req object that has not been instantiated.

Instead of: RestRequest req = RestContext.request;

You need to do RestRequest req = new RestRequest(); (Additionally, the same applies for your res variable).

Related Topic