Test Class for Apex methods making Callouts

Atlassian Jira Jul 18, 2016

Methods defined as TestMethod do not support Web service callouts. This is the error that you will encounter when you run a test for an Apex class that makes a callout. The error being quite descriptive, it becomes obvious that you cannot directly test and/or have a coverage for the piece of code that makes a callout.

Use Test.isRunningTest()

So is there no way to have above 75% coverage and push such a code (that makes a callout) to production environment. Test.isRunningTest() comes to rescue. This method returns true if the currently executing code was called by code contained in a test method, false otherwise. So the workaround is simply to enclose the code blocks that are related to a Callout in an if condition as shown below.

HttpResponse res;
String JSONContent = '<sample JSON string of the response>';
  req.setEndpoint('<endpoint url>');
  res = http.send(req);
  JSONContent = res.getBody();

The callout code will be executed only when the execution isn't from a test context; in which case the hard-coded JSON string will be used as JSON content. Make sure that you pass a real JSON string so that there is sufficient coverage without any Null pointer exceptions.


Integration enthusiast started Inteygrate.com to collaborate with fellow Salesforce-ians trying hands at developing Integration Solutions for connecting Salesforce to the World