Skip to content

Instantly share code, notes, and snippets.

@noeticpenguin
Created October 19, 2011 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save noeticpenguin/1299269 to your computer and use it in GitHub Desktop.
Save noeticpenguin/1299269 to your computer and use it in GitHub Desktop.
Writing and testing restful web callouts from Salesforce.com
public with sharing class DemoWebCallout {
public class applicationException extends Exception {}
Public static HttpRequest buildRequest(Lead l){
HttpRequest request = new HttpRequest();
String url = 'http://www.pinguinshow.com/';
request.setEndpoint(url);
request.setMethod('GET');
return request;
}
public static HttpResponse makeRequest(Http h, HttpRequest request){
HttpResponse response = h.send(request);
return response;
}
public void handleResponse(HttpResponse response){
// For the purpose of this contrived example, we'll not do anything with the response.
// If this were not a contrived example, you might see references to:
// handling xml and other pointy markups languages
// handling JSON -- if you're on Winter 12. More on that later.
}
@future(callout=true)
Public static void makeWebCallout(Id id) {
if(id == null) return;
Lead[] l = [Select l.id From Lead l where l.id = :id limit 1];
if(!l.isEmpty() || test.isRunningTest()) {
Http h = new Http(); //Create a new http object
try {
HttpRequest request = buildRequest(l[0]); // during a test with a bad id, this will throw an exception
HttpResponse response = makeRequest(h, request);
} catch(Exception e){
System.debug('Failed to execute callout! NO DONUT FOR YOU!! ' + l);
}
}
}
}
@isTest
private class TestDemoWebCallout {
static testMethod void testRestfulCallout() {
Lead l = new Lead();
l.Status = 'Open';
l.LastName = 'Owen';
l.FirstName = 'Bob';
l.Street = '1234 Sesame Street';
l.City = 'Houston';
l.Company = 'Test McTesterson and Co.';
l.State = 'Tx';
l.PostalCode = '27384';
insert l;
Test.startTest();
DemoWebCallout AwesomeDemo = new DemoWebCallout();
HttpRequest testRequest = DemoWebCallout.buildRequest(l);
System.assertEquals('GET', testRequest.getMethod());
System.assertEquals('http://www.pinguinshow.com/', testRequest.getEndpoint());
// working call
DemoWebCallout.makeWebCallout(l.id);
//failing call
DemoWebCallout.makeWebCallout('00QC000000qnwbGMAQ'); //this id should not exist.
Test.stopTest();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment