Created
September 8, 2013 11:31
-
-
Save tyoshikawa1106/6484030 to your computer and use it in GitHub Desktop.
Testing HTTP Callouts by Implementing the HttpCalloutMock Interface : http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_http_testing_httpcalloutmock.htm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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