Skip to content

Instantly share code, notes, and snippets.

@sf-wilson
Forked from tyoshikawa1106/01_CalloutClass.cls
Created June 25, 2021 02:23
Show Gist options
  • Save sf-wilson/eed6c7099c1e5fcf59ed30f4eb02593a to your computer and use it in GitHub Desktop.
Save sf-wilson/eed6c7099c1e5fcf59ed30f4eb02593a to your computer and use it in GitHub Desktop.
public class CalloutClass {
public static HttpResponse getInfoFromExternalService() {
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api.salesforce.com/foo/bar');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
System.assertEquals('GET', req.getMethod());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"foo":"bar"}');
res.setStatusCode(200);
return res;
}
}
@isTest
private class CalloutClassTest {
@isTest static void testCallout() {
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
HttpResponse res = CalloutClass.getInfoFromExternalService();
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '{"foo":"bar"}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment