How to Unit Test Callouts in Apex?

Question:
How do I unit test Apex code that includes a SOAP or REST-based callout or indirectly calls code that makes a callout? I am getting an error saying that callouts are not supported during test execution.
Answer:
Salesforce enforces test isolation, which means you cannot make REST or SOAP callouts during test execution. This restriction applies to all code executed within a test context, whether it directly or indirectly attempts a callout. To test code that performs callouts, you must use a Mock class to simulate the behavior of the remote server and provide a mock response.
CRS Info Solutions in Ahmedabad offers expert-led Salesforce Training in Ahmedabad with hands-on projects—join today for a free demo and boost your skills!!!
Salesforce provides interfaces for mocking callouts:
- HttpCalloutMock for REST callouts.
- WebServiceMock for SOAP callouts.
You must implement these interfaces to define the mock behavior. Additionally, Salesforce offers the built-in StaticResourceCalloutMock and MultiStaticResourceCalloutMock classes, which let you use Static Resources to store mock responses for your tests.
Example 1: Mocking a REST Callout Using HttpCalloutMock
Here’s an example of how to mock a REST callout:
Production Code:
public class CalloutExample {
public static String makeRestCall() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/api/resource');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
return res.getBody();
}
}Mock Class:
public class MockHttpResponse implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"message": "Mock response"}');
return res;
}
}Unit Test:
@IsTest
public class CalloutExampleTest {
@IsTest
static void testMakeRestCall() {
Test.setMock(HttpCalloutMock.class, new MockHttpResponse());
String response = CalloutExample.makeRestCall();
System.assertEquals('{"message": "Mock response"}', response);
}
}Example 2: Mocking a SOAP Callout Using WebServiceMock
Production Code:
global class SoapCalloutExample {
webService static String makeSoapCall(String input) {
// Callout logic here
return null; // Actual implementation omitted
}
}Mock Class:
global class MockSoapResponse implements WebServiceMock {
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName
) {
response.put('result', 'Mocked Response');
}
}Unit Test:
@IsTest
global class SoapCalloutExampleTest {
@IsTest
static void testMakeSoapCall() {
Test.setMock(WebServiceMock.class, new MockSoapResponse());
String result = SoapCalloutExample.makeSoapCall('TestInput');
System.assertEquals('Mocked Response', result);
}
}Using Static Resources for Mock Responses
To simplify mocking for REST callouts, you can use the StaticResourceCalloutMock. Store the mock response in a Static Resource file and reference it in your test.
Example:
@IsTest
public class StaticResourceMockTest {
@IsTest
static void testWithStaticResourceMock() {
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('MockResponse');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);
String response = CalloutExample.makeRestCall();
System.assert(response.contains('Mock data'), 'Response did not contain expected mock data');
}
}By using these approaches, you can test all possible scenarios, including different response bodies and status codes, without violating Salesforce’s test isolation rules.
Accelerate Your Salesforce Career with Training in Ahmedabad
Unlock new career opportunities with Salesforce through expert-led Salesforce online training from CRS Info Solutions in Ahmedabad. Our comprehensive courses cover essential areas like Salesforce Admin, Developer, and AI modules, emphasizing real-time project-based learning to equip you with practical skills. Whether you’re a beginner or looking to enhance your expertise, our industry-focused curriculum ensures you gain the knowledge and confidence needed to thrive in the Salesforce ecosystem. Led by experienced professionals, our program prepares you for real-world challenges and helps you become job-ready.
Our training offers hands-on learning, personalized mentorship Salesforce Training in Ahmedabad , and resources like detailed class notes, certification guidance, and interview preparation to help you succeed. With a focus on practical application and expert support, you’ll be fully equipped to step into your next Salesforce role.
Don’t miss the chance to advance your career—enroll today and join our free demo session to start your Salesforce journey!!!
See also : Salesforce Testing
Guide to Become a Salesforce Tester

