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.


You've successfully subscribed to inteygrate
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Success! Your account is fully activated, you now have access to all content.