In Salesforce Apex, methods defined as testMethod (or using @isTest) do not support web service callouts because test methods are meant to run in a controlled, isolated environment without making external API requests.
Key Reasons Why Test Methods Don’t Support Callouts
1. Governor Limits & Bulk Testing
- Salesforce enforces strict limits on callouts to prevent excessive API usage.
- If test methods could make real API calls, it could exceed daily limits, causing failures.
2. Isolation from External Systems
- Apex test methods should run independently of external web services.
- A web service being slow, down, or returning different data could break tests.
3. Test Data Integrity
- Test methods use mock data and cannot rely on unpredictable API responses.
- This ensures test results are consistent and repeatable.
How to Handle Callouts in Test Methods?
- Since real callouts are not allowed, Salesforce provides a solution: Mock Callouts using HttpCalloutMock.
- Steps to Use Mock Callouts in Tests
1. Implement a Mock Class
Create a mock class that implements HttpCalloutMock:
@isTest
public class MockCallout implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setBody('{"status": "success"}');
res.setStatusCode(200);
return res;
}
}
2. Use Test.setMock() in the Test Method
Inside the test method, use Test.setMock() to replace real callouts with mock responses:
@isTest
public static void testCalloutMethod() {
Test.setMock(HttpCalloutMock.class, new MockCallout());
// Call the method that performs the callout
String response = MyClass.callExternalService();
System.assertEquals('success', response);
}
Final Thoughts
- Real API calls are not allowed in tests to ensure isolation and prevent failures.
- Use HttpCalloutMock to simulate API responses in test methods.
- Mock callouts keep tests reliable and within Salesforce limits.