You need to sign in to do that
Don't have an account?
Code coverage of apex callout in rest api
Hello guys I am trying to get the code coverage of the apex callout in rest API. Method is getting failed and I am able to achieve only 40% code coverage of the class. Please give your valuable suggestions. Thanks in advance..!
Apex Class
Mock Class :
Test Class :
Apex Class
global with sharing class CreateCasesByContract { global static string GetToken(string userName, string password) { string accessToken; Http client = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('-------------------'); req.setMethod('POST'); string encodedBody = EncodingUtil.urlEncode('grant_type','UTF-8')+'='+EncodingUtil.urlEncode('password','UTF-8')+'&'+EncodingUtil.urlEncode('username','UTF-8')+'='+EncodingUtil.urlEncode(userName, 'UTF-8')+'&'+EncodingUtil.urlEncode('password','UTF-8')+'='+EncodingUtil.urlEncode(password, 'UTF-8'); req.setHeader('content-type', 'application/x-www-form-urlencoded'); req.setBody(encodedBody); HttpResponse res = client.send(req); String Token = res.getBody(); system.debug('J!GS' + Token ); JSONParser parser = JSON.createParser(Token); While(parser.nextToken() != null) { if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)) { String fieldName = parser.getText(); parser.nextToken(); if(fieldName == 'access_token') { accessToken = parser.getText(); } } } return accessToken; } global Integer CreateCase() { Integer C; //Make POST call for getting AssocType object string assocData; String access_token = GetToken('API_Admin','Boxer@123'); Http client = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('------------------'+ System.UserInfo.getName() +'&caseType= 82'); req.setMethod('GET'); req.setHeader('content-type', 'application/json'); req.setHeader('Authorization', 'bearer ' + access_token); HttpResponse res = client.send(req); String assocString = res.getBody(); ApiResponse APIRes = new ApiResponse(); APIRes = (ApiResponse) System.JSON.deserialize(assocString, ApiResponse.class); system.debug('ApiRes object '+ APIRes); string CID2; List<Contract> ConList = [Select id,Property_Manager__c,DueDate__c,Region__c,PROPERTY_CODE__c, BP_Property__r.Name,bp_property_id__c,Region_ID__c, LeasingAgentSAM__c ,BP_Unit__r.Name from Contract where Id =: cid and Broker_Involved__c = 'Yes' ORDER BY LastModifiedDate DESC limit 1]; List<textValuescls> txstring = New List<textValuescls>(); string metadataValue = ''; String CurrentUserofSFstr = UserInfo.getName(); CaseData cd = New CaseData(); //Mapping the Contarct data With AssocDataTypes and Passing parameters. ****for(AssocType AC: APIRes.ResponseContent) { for(Contract C1 : ConList) { CID2 = C1.Id; string CaseTitelstr = C1.PROPERTY_CODE__c + ' X '+ C1.BP_Unit__r.Name + 'Broker Commission Request'; if(AC.Description == 'Property') { metadataValue += AC.AssocTypeID + ',0,' + C1.bp_property_id__c + ',' + AC.Description + ',' + C1.BP_Property__r.Name +'|'; } else if(AC.Description == 'Region') { metadataValue += AC.AssocTypeID + ',0,' + C1.Region_ID__c + ',' + AC.Description +',' + C1.Region__c + '|'; } else if(AC.Description == 'Status') { metadataValue += AC.AssocTypeID + ',3784,0,Status,New '; } else if(Ac.Description == 'Suite') { textValuescls tx1 = new textValuescls(); tx1.key = Ac.AssocTypeID; tx1.value = C1.BP_Unit__r.Name; txstring.add(tx1); } else if(Ac.Description == 'Due Date') { string duedate = string.valueOf(C1.DueDate__c); textValuescls tx2 = new textValuescls(); tx2.key = Ac.AssocTypeID; tx2.value = duedate; txstring.add(tx2); } else if (AC.Description == 'Case Title') { textValuescls tx3 = new textValuescls(); tx3.key = Ac.AssocTypeID; tx3.value = CaseTitelstr; txstring.add(tx3); } cd.currentUser = C1.LeasingAgentSAM__c; cd.metaDataValues = metadataValue ; cd.caseNotes = 'Testing REST API from Salesforce Please ignore this case ' + CurrentUserofSFstr; cd.textValues = txstring; cd.caseTitle = CaseTitelstr; cd.caseType = 82 ; cd.assignTo = 'xyz'; } } //Converting CaseData object and parameters in json fromat String JSONString = JSON.serialize(cd); System.debug('Serialized list of invoices into JSON format: ' + JSONString); Http client1 = new Http(); HttpRequest req1 = new HttpRequest(); req1.setEndpoint('------------------------------'); req1.setMethod('POST'); req1.setHeader('content-type', 'application/json'); req1.setHeader('Authorization', 'bearer ' + access_token); req1.setBody(JSONString); HttpResponse res1 = client1.send(req1); string caseDataFinal = res1.getBody(); system.debug('Final test ' + caseDataFinal); APIResponseCaseData APIResCaseData = new APIResponseCaseData(); APIResCaseData = (APIResponseCaseData) System.JSON.deserialize(caseDataFinal, APIResponseCaseData.class); Integer caseIdFinal = APIResCaseData.ResponseContent; system.debug('Final test ' + caseIdFinal); ID coid = Id.valueOf(CID2); system.debug('^^^^^^^ID^^^^^^' + coid); List<Contract> CList = new List<Contract>(); contract con = new Contract(); //con.Id = coid; con.BCR_Case_Id__c = caseIdFinal; CList.add(con); Update CList; return C; }** }
Mock Class :
global class CreateCasesByContractMock implements HttpCalloutMock { global HTTPResponse respond(HTTPRequest request) { // Create a fake response HttpResponse response = new HttpResponse(); response.setHeader('Content-Type', 'application/json'); response.setBody(' {"caseTitle": "4200t X 520 Broker Commission Request ", "caseType": 82, "assignTo": "JigneshC", "currentUser": "Testing"}'); response.setStatusCode(200); return response; }* }
Test Class :
@isTest Public class TestCreateCasesByContract{ Public Static testmethod void mytest() { Test.setMock(HttpCalloutMock.class, new CreateCasesByContractMock()); HttpResponse response = New HttpResponse (); test.startTest(); CreateCasesByContract.GetToken('userName', 'password'); test.stopTest(); } public static testmethod void testsaveDataToSF() { Test.setMock(HttpCalloutMock.class, new CreateCasesByContractMock()); AssocType AC = New AssocType(); test.startTest(); CreateCasesByContract.CreateCase(); test.stopTest(); }** }
Could please tell me what error are you facing and in which line . Also tell me till which line the code is covered ?
You have not pasted code fo mytest1 function from where the error gets triggered . If you have change the code again in the class CreateCasesByContract . Request you to paste the code of class and test class again .
Also what i can figure out is line no 72 from class APIRes is null and APIRes.ResponseContent will result to null pointer exception . For this you have to check if proper json data is being set for setBody in mock class.