What is the best practice for writing apex test classes where you have multiple callouts? My Test Class would then be testing the secondCallout method which happens to also call a firstCallout method that has a callout in itself. My question is, what is the appropriate way to be able to run the mock test for both methods?
Main Class
public class myclass {
public static String firstCallOut() {
HttpRequest req = new HttpRequest ();
HttpResponse res = new HttpResponse();
req.setMethod('POST');
//code snippets only
return res.getBody().
}
public static void secondCallOut() {
String resultFromFirstCallout = firstCallOut();
HttpRequest req = new HttpRequest ();
req.setMethod('POST');
req.setBody(resultFromFirstCallout);
//code snippets only
}
}
Mock Class
public with sharing class MyMockclass implements HttpCalloutMock {
protected Integer code;
protected String status;
protected String body;
protected Map<String, String> responseHeaders;
public MyMockclass (Integer code, String status, String body, Map<String, String> responseHeaders) {
this.code = code;
this.status = status;
this.body = body;
this.responseHeaders = responseHeaders;
}
public HTTPResponse respond(HTTPRequest request) {
// Create a fake response
HttpResponse response = new HttpResponse();
for (String key : this.responseHeaders.keySet()) {
response.setHeader(key, this.responseHeaders.get(key));
}
response.setBody(this.body);
response.setStatusCode(this.code);
response.setStatus(this.status);
return response;
}
}
Test Class
@isTest(seeAllData=false)
public class myclassTest{
static testMethod void myTestMethod(){
Map<String, String> responseHeader = new Map<String, String>();
responseHeader .put('Content-Type','application/json');
MyMockclass mock= new MyMockclass (
200,
'success',
'Succesful',
responseHeader
);
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
myclass.secondCallOut();
Test.stopTest();
}