1

I am trying to write a test class for my rest resource and I keep getting a failure with the above error message. I've seen other anwsers suggest that there may be a '' escape character in the text, but I don't see that anywhere.

Here is my test class:

    @isTest static void testAuthCallout() {
    Test.setMock(HttpCalloutMock.class, new CFM_API_D2CInventory_MockHttpGenerator());

    HttpResponse response = CFM_API_D2CInventory_GetAuth.getAuth();

    String contentType = response.getHeader('Content-Type');
    String authorization = response.getHeader('Authorization');
    String body = response.getBody();
    
    System.assert(contentType == 'application/json');
    System.assert(authorization == 'bearerauthtoken123456789');
    System.assert(body == 'SUCCESS');
    System.assertEquals(200, response.getStatusCode());
}

Here is the method I'm testing:

    global static HttpResponse getAuth(){

    HttpRequest request = new HttpRequest();
    request.setMethod('POST');
    request.setEndpoint('callout:someCallout');


    Http http = new Http();

    HttpResponse response = http.send(request);

    Map<String, Object> bearerTokenMap = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());

    String bearerToken = 'Bearer '+(string) bearerTokenMap.get('access_token');

    CFM_API_D2CInventory_RequestURI.RequestURI(bearerToken);
    return response;
}

And here is the response body that seems to be causing the issue:

{"access_token":"eyJ0eXAiOiJKV1QiLCJraWQiOiJEMWhPUDdEODN4TjBqZWlqaTI3WWFvZFRjL0E9IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJlZDU0ZjdmNS05OWQ5LTQ5ZGMtODA4MC0wMGI5MmJiNTdjYmUiLCJjdHMiOiJPQVVUSDJfU1RBVEVMRVNTX0dSQU5UIiwiYXVkaXRUcmFja2luZ0lkIjoiNjQwNGYxNTktZmM5My00OTBhLTg4YTMtNDA2OWQ0MzdhYjQ1LTg1MjM0NDQ5Iiwic3VibmFtZSI6ImVkNTRmN2Y1LTk5ZDktNDlkYy04MDgwLTAwYjkyYmI1N2NiZSIsImlzcyI6Imh0dHBzOi8vYWNjb3VudC5kZW1hbmR3YXJlLmNvbTo0NDMvZHdzc28vb2F1dGgyIiwidG9rZW5OYW1lIjoiYWNjZXNzX3Rva2VuIiwidG9rZW5fdHlwZSI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SIsIkNDRFhfU0JYX1VTRVIiXX0.MTuYWSnANy9a5DRyUCIAjYb08JhCc2jJfxBoDAXo3m8SqqLsY6n5ClwULurzezADwdFkcaJYyO-usnJgDX6BHCeHCdWEPADz4XYIqVo0oJUlaUGE1e_2u4zxgSi2GpcNYenbmWL7mqWzDokk0WE78pKDYGJmOor0aigB8bymSM0BmBOv0aBeUZWiYzZNogo2ijOd_0URqw4RIpeLLuswClD-y-YG75LFaWlkVBQMhI-jwKGhUqeyYhZcT2VdIafHbyTUiJub8bjLDVplMnt5S4gjRt8SmbiD4GiAz86m3n1n_A_0caj7OwG1HSdYjXX_ZkCag2NiGlxPGPbdniCjqg","scope":"sfcc.shopper-products sfcc.inventory.availability.rw sfcc.inventory.impex-inventory.rw mail openId sfcc.products.rw profile roles sfcc.inventory.impex-graphs sfcc.inventory.reservations.rw sfcc.cdn-zones.rw tenantFilter SALESFORCE_COMMERCE_API:abcd_abc","token_type":"Bearer","expires_in":1799}
17:10:59.12 (431845997)|STATEMENT_EXECUTE|[16]
17:10:59.12 (431968888)|HEAP_ALLOCATE|[16]|Bytes:2227

As requested, here's the code for the MockHttpGenerator:

@isTest
public class CFM_API_D2CInventory_MockHttpGenerator implements HttpCalloutMock{
        public HttpResponse respond(HTTPRequest request) {
            HttpResponse response = new HttpResponse();
            response.setHeader('Content-Type', 'application/json');
            response.setHeader('Authorization', 'bearerauthtoken123456789');
            response.setBody('SUCCESS');
            response.setStatusCode(200);
            return response;
        }
    }

Code for RequestURI Method:

@RestResource(urlMapping='/D2C/RequestURI')
global with sharing class CFM_API_D2CInventory_RequestURI {

    global static HttpResponse RequestURI(String bearerToken){

        System.debug('Requesting Upload Link');

        List<String> jsonStrings = new List<String>();
        Map<String, Object> JSON_URI = new Map<String, Object>();

        // Set the fields in the JSON object
        JSON_URI.put('fileName', 'cfm_inventory.json');
        JSON_URI.put('linkDuration', 1);
        JSON_URI.put('fileFormat', 'JSON');

        // Convert the JSON object to a string
        String jsonString = JSON.serialize(JSON_URI);

        // Add the string to the list
        jsonStrings.add(jsonString);

        String finalJson = String.join(jsonStrings, ',');

        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setMethod('POST');
        request.setEndpoint('https://US.api.commercecloud.salesforce.com/inventory/impex/v1/organizations/12345/availability-records/imports');
        request.setHeader('Authorization', bearertoken);
        request.setHeader('content-type', 'application/JSON');
        request.setBody(finalJson);

        System.debug('URI Request: '+request);

        HttpResponse response = http.send(request);

        if(response.getStatusCode() != 200) { 
            System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' + response.getStatus());
        } else {

            System.debug('RequestURI Response: '+response.getBody());

            Map<String, Object> URIMap = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            String uploadLink = 'https://US.api.commercecloud.salesforce.com'+(string) URIMap.get('uploadLink');

            System.debug('Upload Link: '+uploadLink);

            CFM_API_D2CInventory_PostInventoryUpdate.PostInventoryUpdate(bearerToken, uploadLink);
        }
        return response;
    }
}
2
  • Please edit your question to include the code for CFM_API_D2CInventory_MockHttpGenerator. That's probably where the issue is.
    – Derek F
    Jun 2, 2023 at 22:05
  • @DerekF I added that now as well. It's pretty bare bones though.
    – Ryan Neel
    Jun 2, 2023 at 22:10

1 Answer 1

1

It seems like the problem is the CFM_API_D2CInventory_MockHttpGenerator class.

When you are setting the body of the response, you are only setting it to the string 'SUCCESS', and then the method getAuth() tries to deserialize 'SUCCESS' as a JSON here:

Map<String, Object> bearerTokenMap = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());

But the string 'SUCCESS' is not a JSON. That is why you are getting the System.JSONException error message.

The response body in CFM_API_D2CInventory_MockHttpGenerator should be more like this (which is a JSON):

'{"access_token":"YOUR_ACCESS_TOKEN","scope":"sfcc.shopper-products sfcc.inventory.availability.rw sfcc.inventory.impex-inventory.rw mail openId sfcc.products.rw profile roles sfcc.inventory.impex-graphs sfcc.inventory.reservations.rw sfcc.cdn-zones.rw tenantFilter SALESFORCE_COMMERCE_API:abcd_abc","token_type":"Bearer","expires_in":1799}'

Hoping this helps!

8
  • That fixed the error I was reporting in this issue, but now I'm receiving another error stating: "System.StringException: Starting position out of bounds: -3"
    – Ryan Neel
    Jun 2, 2023 at 22:58
  • @RyanNeel is there a line in the code where the error is being thrown? Jun 2, 2023 at 23:03
  • Looks like line 20 of the getAuth method, which I remove some debug statements from in the example above, it's the statment in the getAuth method that reads "CFM_API_D2CInventory_RequestURI.RequestURI(bearerToken)"
    – Ryan Neel
    Jun 2, 2023 at 23:07
  • Please, provide the code for the method CFM_API_D2CInventory_RequestURI.RequestURI(bearerToken) @RyanNeel Jun 2, 2023 at 23:10
  • Just posted it above.
    – Ryan Neel
    Jun 2, 2023 at 23:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .