0

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();
}
3
  • Hello and welcome to SFSE community! Could you share the stack trace to understand which specific line is triggering the null pointer exception? Dec 14, 2021 at 9:34
  • getting null pointer exception at this line-> req.requestURI = '/services/apexrest/demoURL';
    – user104634
    Dec 14, 2021 at 9:36
  • 1
    Hello Sagar, and welcome, does this answer help you? I believe the problem is that you need to instantiate the request prior to attempt to set the requestURI and httpMethod. Dec 14, 2021 at 10:57

1 Answer 1

0

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).

1
  • thanks it worked!
    – user104634
    Dec 14, 2021 at 11:41

You must log in to answer this question.