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
Simon234Simon234 

How can I test my Web Token and posted record from Post Callout?

I try to use HttpCalloutMock to test my post callout. But I become System.NullPointerException: Attempt to de-reference a null object. I need to test and web token, and posted object. I'm just learning and don't understand how actually use a Mock in this situation. Callout:
public class Token{
public String accessToken{get;set;}    
}

public static String accessTokenBody(){  //our web token (data is in fields)
        Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                                FROM Settings__c
                                WHERE Name = 'OurSettings'];  
        String consumerKey = settings.ConsumerKey__c;
        String consumerSecret = settings.ClientSecret__c;
        String username = settings.Username__c;
        String password = settings.Password__c + settings.SecurityToken__c;
        String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                         '&username=' + username + '&password='+password;
        return request;
    }

public static String GenerateJSON(Type__c t){
//I will send and post it like a record in another org:
    Map<String, String> fieldMap = new Map<String, String>{
                   'Name' => t.Name,
                   'Desc__c' => t.Type_Description__c};    
    String serialized = JSON.serialize(fieldMap);         
    return serialized;
 }

public static HttpRequest httpRequest(String service){
    String requestBody = accessTokenBody();
    HttpRequest ourRequest = new HttpRequest();
    ourRequest.setBody(requestBody);
    ourRequest.setMethod(service);
    ourRequest.setEndpoint('https://p21.lightning.force.com/services/oauth2/token');
    return ourRequest;
}

public static HttpRequest finalHttpRequest(String token, String method, String endpointUrl){
    HttpRequest finalRequest = new HttpRequest();
    finalRequest.setHeader('Authorization','Bearer ' + token);
    finalRequest.setHeader('Content-Type','application/json');
    finalRequest.setHeader('accept','application/json');
    finalRequest.setMethod(method);
    finalRequest.setEndpoint('https://p21.lightning.force.com/services/oauth2/token' + endpointUrl);
    return finalRequest;
}

public static HttpResponse postCallout(String positionId) {
    Http ourHttp = new Http();
    HttpRequest request = httpRequest('POST');
    HttpResponse response = ourHttp.send(request);      
    Token objAuthenticationInfo = (Token)JSON.deserialize(response.getbody(), Token.class);

    if(objAuthenticationInfo.ACCESS_TOKEN != null){
        Type__c typ = [SELECT Id, Name FROM Type__c WHERE Id =: TypeID];
        HttpRequest finalRequest = finalHttpRequest(objAuthenticationInfo.ACCESS_TOKEN, 'POST', '');
        finalRequest.setBody(GenerateJSON(typ));
        HttpResponse finalResponse = ourHttp.send(finalRequest);
        if(finalResponse.getStatusCode() == 200) {
            System.debug('CREATED:  ' + finalResponse.getBody());
            return finalResponse;
        }else {
            return null;
        }
    }
    return null;
}
Mock:
@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest request) {
    HttpResponse response = new HttpResponse();
    response.setHeader('Content-Type', 'application/json');
    Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, 
                        Password__c, SecurityToken__c
                        FROM Settings__c
                        WHERE Name = 'OurSettings'];
        String serialized = JSON.serialize(settings);
        response.setBody(serialized);
        response.setStatusCode(200);
        return response;
}
}
Test:
@isTest
private class CalloutTest {

@isTest
static void testPostCallout() {              
    Settings__c settings = new Settings__c(Name = 'OurSettings',
                                           ConsumerKey__c = '****',
                                           ClientSecret__c = '*****',
                                           Username__c = '*****',
                                           SecurityToken__c = '****',
                                           Password__c = 'mypassword1');
    insert settings;

    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;

    Type__c typ = new Type__c(Name = 'ttt');
    insert typ;

    Http ourHttp = new Http();
    String requestBody = CalloutJobAdvertisement.accessTokenBody();
    System.debug('request: ' + request);
    System.debug('request2: ' + requestBody);
    HttpRequest ourRequest = new HttpRequest();
    ourRequest.setBody(requestBody);
    ourRequest.setMethod('POST');
    ourRequest.setEndpoint('https://p21.salesforce.com/services/oauth2/token');    
    Test.startTest(); 
    Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());
    HttpResponse response = CalloutJobAdvertisement.postCalloutResponseContents(pos.Id);

//Error is here. System.NullPointerException: Attempt to de-reference a null object

    String contentType = response.getHeader('Content-Type');
    System.assert(contentType == 'application/json');
    String actualValue = response.getBody();
    System.debug(response.getBody());
    String expectedValue = '{"Name":"ttt"}';
    System.assertEquals(actualValue, expectedValue);
    System.assertEquals(200, response.getStatusCode());
    Test.stopTest(); 
}

public class OAuth2{
    public String ACCESS_TOKEN{get;set;}    
}
}
Coverage is just on my getAccess()httpRequest() and 5 first rows of postCallout() + last row return null;

 
Raj VakatiRaj Vakati
Change your code Mock test as shown below and try 
 
@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest request) {
    HttpResponse response = new HttpResponse();
    response.setHeader('Content-Type', 'application/json');
    
	Settings__c settings = new Settings__c(Name = 'OurSettings',
                                           ConsumerKey__c = '****',
                                           ClientSecret__c = '*****',
                                           Username__c = '*****',
                                           SecurityToken__c = '****',
                                           Password__c = 'mypassword1');
    insert settings;
	
	
        String serialized = JSON.serialize(settings);
        response.setBody(serialized);
        response.setStatusCode(200);
        return response;
}
}