Inteygrate

Test Class for Apex methods making Callouts

Introduction

Muralidhar

Muralidhar

At inteygrate.com, I am trying out ways to integrate Salesforce to various other technologies.


Apex Callouts salesforce-jira integration Salesforce REST API test class

Test Class for Apex methods making Callouts

Posted by Muralidhar on .
Featured

Apex Callouts salesforce-jira integration Salesforce REST API test class

Test Class for Apex methods making Callouts

Posted by Muralidhar on .

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>';

if(!Test.isRunningTest()){  
  req.setEndpoint('<endpoint url>');
  req.setMethod('GET');
  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.


Muralidhar

Muralidhar

https://inteygrate.com

At inteygrate.com, I am trying out ways to integrate Salesforce to various other technologies.

View Comments...