I'm having difficulty passing a paramater to a HttpCalloutMock class. I have a trigger that calls a future callout on insert and on the response I'm receiving the record id so I can do the relevant record updates. this works fine but when I try to test it I can't pass the Id of the record to the mock class as I'm declaring it before I insert it. Am I going about it the wrong way or is there a workaround? here is the code snippet:
@isTest
public static void testNewCaseInsert(){
Id user = [SELECT id FROM User WHERE FirstName = 'TestUser' LIMIT 1].id;
Id myPlusRTypeId = [SELECT id FROM RecordType WHERE developerName = 'Test_Plus' LIMIT 1].id;
Id contactId = [SELECT id FROM Contact WHERE FirstName = 'Contact' LIMIT 1].id;
Case caseMPlus = new Case(
RecordTypeId = myPlusRTypeId,
OwnerId = user,
Status = 'New',
Priority = 'Medium',
ContactId = contactId,
Origin = 'Email',
Subject = 'Subject Mail Plus',
Description = 'watermelons',
);
test.setMock(HttpCalloutMock.class, new MockResponse(caseMPlus.id));//I can't pass case Id without inserting it first
test.startTest();
insert caseMPlus;
test.stopTest();
}
And here is the Mock class:
@isTest
public class LimitlessMockResponse implements HttpCalloutMock {
protected Id caseId;
public LimitlessMockResponse(Id caseId){
this.caseId = caseId;
}
public HTTPResponse respond(HTTPRequest req) {
System.assertEquals('callout:Limitless', req.getEndpoint());
System.assertEquals('POST', req.getMethod());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
//trying to pass the caseId into the body to assert against the response
res.setBody('{"count": 1,"success": 1,"failed": 0,"messages": [{"tenantMsgId":'+'"'+caseId+'","rejectReasonCode": "no group found","processCode": "ACC"}]}');
res.setStatusCode(200);
return res;
}
}
Here is the logic part:
public static void handleResponse(String rBody){
List<Case>updateCases = new List<Case>();
LimitlessDataResponse dResponse = LimitlessDataResponse.parse(rBody);
//Loop through the cases on the response and update
for(DataResponse.Messages r : dResponse.messages){
//Here is where I'm using the case Id from the response to matchup against
Case c = new case (id = r.tenantMsgId,
Sync_Status__c = r.processCode == 'ACC' ? 'Synced' : 'Failed',
Sync_Failed_Reason__c = r.rejectReasonCode,
Retry__c = FALSE
);
system.debug('ResponseData:'+ r.processCode +' '+r.tenantMsgId);
updateCases.add(c);
}
if(!updateCases.isEmpty()){
try{
update updateCases;
}catch(DmlException e){
system.debug('There was an error handling the reponse:'+ e.getMessage());
}
}
}