I am trying to write the Test Class for the Apex Callout which uses the OAuth. The Apex Class with the future method is like below
@future (callout=true)
public static void createSegSubSegment(String jsonBody,String endPoint) {
String clientId = '';
String clientSecret = '';
String resource = '';
String tenant_id = '';
String bearerToken = '';
try{
ExtCred__c[] ExtCred_Data = [SELECT Client_ID__c,Client_Secret__c,Resource__c,Tenant_ID__c from ExtCred__c where Name = 'ThirdParty' ];
if( ExtCred_Data.size() > 0 )
{
clientId = ExtCred_Data[0].Client_ID__c;
clientSecret = ExtCred_Data[0].Client_Secret__c;
resource = ExtCred_Data[0].Resource__c;
tenant_id = ExtCred_Data[0].Tenant_ID__c;
String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret+'&tenant_id='+tenant_id+'&resource='+resource;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://login.microsoftonline.com/abc.org/oauth2/token');
HttpResponse res = h.send(req);
deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
bearerToken = resp1.access_token;
Http http1 = new Http();
HttpRequest req1 = new HttpRequest();
String d365EndPoint = resource + endPoint;
req1.setMethod('POST');
req1.setTimeout(20000);
req1.setHeader('Authorization','Bearer '+bearerToken);
req1.setEndpoint(d365EndPoint);
req1.setBody(jsonBody);
req1.setHeader('Content-Type', 'application/json;charset=UTF-8');
HttpResponse res1 = http1.send(req1);
}
}
I tried to create a global test class which implements HttpCalloutMock like below
@isTest
global class HttpMockCalloutTest implements HttpCalloutMock{
global HttpResponse respond(HTTPRequest req){
HttpResponse res = new HttpResponse();
res.setStatus('OK');
res.setStatusCode(200);
res.setBody('Test Mock Callout');
return res;
}
}
And the actual test class for the Apex Class like
private static testMethod void callFutureMethod() {
ID parentRecType = '012U0000000PqA9IAK';
Account pa = new Account(Name='TestCallOut', recordTypeId=parentRecType,Data_Source_ID__c = 'TestPAX123');
insert pa;
Account acc = [Select id,Data_Source_ID__c from Account where Name like '%TestCallOut%'];
SegJSON js = new SegJSON();
js.dataAreaId = '123';
js.SegmentCode = acc.Data_Source_ID__c ;
String jsonBody = json.serialize(js);
String endPoint = '/data/parentAccounts';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new HttpMockCalloutTest());
handleD365Request.createSegSubSegment(jsonBody,endPoint);
Test.stopTest();
}
public class SegJSON {
public String dataAreaId;
public String SegmentCode;
public SegJSON parse(String json) {
return (SegJSON) System.JSON.deserialize(json, SegJSON.class);
}
}
Even though when I run the test class it says successful but when I see the no code coverage. I see none of the line are covered starting from my if block if( ExtCred_Data.size() > 0 )