0

Taking into consideration the below pseudo code, do we need to check if an apex test is running before performing callout? Or does the Test.setMock() method automatically prevent callouts during a test run?

static void performCallout(){
  HttpRequest req = new HttpRequest();
  req.setEndpoint(url);
  req.setMethod(method);
  req.setBody(body);
  Http http = new Http();
  //Do I need to check if test is running here by using 
  //Test.isRunningTest() so that I do not receive error during testing?
  HttpResponse res = http.send(req);
}
Test.Start();
Test.setMock(HttpCalloutMock() mock, <class utilizing HttpCalloutMock interface>);
//call method that performs callout to external service
performCallout();
Test.Stop();

This documentation seems to imply that by using Test.setMock() inside your test class you do not need to check if a test is running before performing a callout because the method will "send a mock response whenever a callout is made through the HTTP classes." See below for relevant portion:

Sets the response mock mode and instructs the Apex runtime to send a mock response whenever a callout is made through the HTTP classes or the auto-generated code from WSDLs.

1 Answer 1

4

do we need to check if an apex test is running before performing callout? Or does the Test.setMock() method automatically prevent callouts during a test run?

You do not need to change your code under test if you correctly use Test.setMock(). In fact, doing so results in your mocks never being called, which diminishes the utility of your tests. Set mocks and test your real code paths!

2
  • Thank you for quick response. So both 1 and 2 below are true assuming class that implements HttpCalloutMock is setup correctly? 1) Test.setMock() will send a mock response if a callout is made during testing 2) Test.isRunningTest() is not necessary to prohibit a callout from being made during a test Sep 2 at 22:21
  • That is correct.
    – David Reed
    Sep 2 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.