Here is some background- I have an apex future method which is being called from an trigger. The future method then performs 3 different http calls to an external system (same endpoints). All requests have different body. Here is how it looks like-
public Static Void MyCallOut{
String session= callout1();
callout2(session);
If(condition)
callout3(session);
else
callout4(session);
}
Everything works well.
I am trying to write test class for this using "HttpCalloutMock Interface", and using this as reference.
Here is my MockHttpResponseGenerator, which I intend to call from my test class-
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock{
// Implement this interface method
global HTTPResponse respond(HTTPRequest req) {
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'text/xml');
res.setBody('<soapenv:Envelope>'+
'<soapenv:Body><re:sessionId>BBE099E0392E6509B43</re:sessionId>'+
'</soapenv:Body></soapenv:Envelope>');
res.setStatusCode(200);
return res;
}
}
Now my questions is, How can I or Is there a way to make it work so that the HttpCalloutMock returns different responses for different calls? or Is there something I am missing?
P.S. I know this can be achieved by having separate mockcallresponse class to be called from the main class when isRunningTest is true. But, I want to if the same can be achieved without contaminating my main code.
Thanks
Best Answer
Salesforce passes in the HTTPRequest made by the logic your testing into the mock implementation to help with this type of requirement. So in the HttpCalloutMock.respond method implementation. You can call req.getBody() and condition the response based on that, here is an example...