Traditionally, testing Apex code that interacts with external web services required using HttpCalloutMock or WebServiceMock. While mocks are essential for unit testing and code coverage, they do not validate live network connectivity, actual authentication header handshakes, or unexpected changes in third-party payload schemas.
Salesforce introduced Apex Integration Tests (@IntegrationTest), allowing developers to execute real HTTP callouts directly from supported scratch orgs.
In this guide, we will explore how @IntegrationTest works, how it handles data cleanup, and how to execute integration test suites via the Salesforce CLI.
What Is @IntegrationTest in Salesforce Apex?
The @IntegrationTest annotation designates a test class or method specifically for real-world integration testing.
Unlike standard Apex unit tests marked with @isTest, integration tests offer the following capabilities:
- Real Callouts Allowed: You can send live HTTP requests to external endpoints without registering a mock.
- Excluded from Code Coverage: Integration tests validate live service contracts rather than code path coverage metrics for deployment.
- Asynchronous Execution: Tests execute asynchronously in supported scratch org environments.
Scratch Org Requirement
To use @IntegrationTest, you must enable the ApexIntegrationTests feature in your scratch org definition file (project-scratch-def.json):
{
"orgName": "Integration Test Org",
"edition": "Developer",
"features": ["ApexIntegrationTests"]
}
Data Management: @BeforeClass, @TearDown, and Manual Rollback
Standard unit tests (@isTest) automatically roll back DML operations at the end of execution. However, because @IntegrationTest runs live integration transactions across system boundaries, automatic rollbacks operate differently.
To manage setup and cleanup explicitly, use lifecycle annotations:
- @BeforeClass: Executes once before any test methods run in the integration test class to prepare required test records.
- @TearDown: Executes after test execution completes. Because live integration data can persist across operations, explicit cleanup in @TearDown ensures your environment remains clean.
Apex Integration Test Implementation
@IntegrationTest
public with sharing class CustomerApiIntegrationTest {
private static final String TEST_NAME = 'Integration Test Customer';
@BeforeClass
public static void setup() {
Account account = new Account(Name = TEST_NAME);
insert account;
}
@IntegrationTest
public static void testCustomerApi() {
Account account = [
SELECT Id, Name
FROM Account
WHERE Name = :TEST_NAME
LIMIT 1
];
System.assertNotEquals(
null,
account.Id,
'Account should exist in the target org.'
);
}
@TearDown
public static void cleanup() {
List<Account> accounts = [
SELECT Id
FROM Account
WHERE Name = :TEST_NAME
];
if (!accounts.isEmpty()) {
delete accounts;
}
}
}
Performing Live External API Callouts
When testing live endpoints, combine @IntegrationTest with Named Credentials (callout:Public_JSONPlaceholder) to handle endpoint routing and authorization seamlessly.
Service Class
public with sharing class ExternalPostService {
public static Map<String, Object> getPost(Integer postId) {
HttpRequest request = new HttpRequest();
request.setEndpoint(
'callout:Public_JSONPlaceholder/posts/' + postId
);
request.setMethod('GET');
request.setHeader('Accept', 'application/json');
request.setTimeout(30000);
Http http = new Http();
HttpResponse response = http.send(request);
if (response.getStatusCode() != 200) {
throw new CalloutException(
'External API returned status: ' +
response.getStatusCode()
);
}
return (Map<String, Object>)
JSON.deserializeUntyped(response.getBody());
}
}
Real Callout Integration Test
@IntegrationTest
public with sharing class ExternalPostIntegrationTest {
@IntegrationTest
public static void testRealExternalApiCallout() {
// Sends an actual HTTP GET request to JSONPlaceholder
Map<String, Object> result =
ExternalPostService.getPost(1);
System.assertEquals(
1,
result.get('id'),
'Post ID should match the requested record.'
);
System.assertNotEquals(
null,
result.get('title'),
'API response should contain a title.'
);
System.assertNotEquals(
null,
result.get('body'),
'API response should contain a body.'
);
}
}
Executing Apex Integration Tests via Salesforce CLI
Run integration test suites from your terminal targeting your integration test scratch org:
sf apex run test --tests testClassName --target-org orgName --result-format human --wait 10
Key Performance Insights
- Setup Phase (@BeforeClass): The setup method executed in 101 ms, creating the baseline records required for execution.
- Execution Phase (@IntegrationTest): The test logic verified record presence in 11 ms.
- Cleanup Phase (@TearDown): The tear-down logic removed created records, ensuring no leftover test data polluted the org.
Best Practices for Salesforce Apex Integration Testing
- Use Unit Tests (@isTest) for Deployments: Keep @isTest with mocks for code coverage requirements during production deployments.
- Use @IntegrationTest for End-to-End Validation: Run live @IntegrationTest suites in CI/CD pipelines against sandbox/scratch environments to detect third-party API breaking changes early.
- Always Implement @TearDown: Ensure integration tests clean up persistent records created during testing.
Conclusion
Salesforce Apex Integration Testing with @IntegrationTest provides developers with an approach to validate real-time interactions between Salesforce and external APIs. By performing live HTTP callouts, managing test data with lifecycle annotations, and executing tests through the Salesforce CLI, developers can identify integration issues and unexpected API changes more effectively. While traditional Apex unit tests remain essential for code coverage and deployment requirements, integration tests add another layer of validation by testing actual external service interactions. By following the above best practices, developers can build more reliable, maintainable, and efficient Salesforce integrations.
By following the above blog instructions, you will be able to learn “Salesforce Apex Integration Testing: Run Real API Callouts Using @IntegrationTest“. If you still have queries or any related problems, don’t hesitate to contact us at [email protected]. More details about our integration product are available on our website and Salesforce AppExchange.
We hope you may find this blog resourceful and helpful. However, if you still have concerns and need more help, please contact us at [email protected].
About Us
Greytrix – a globally recognized and one of the oldest Sage Development Partner and a Salesforce Product development partner offers a wide variety of integration products and services to the end users as well as to the Partners and Sage PSG across the globe. We offer Consultation, Configuration, Training and support services in out-of-the-box functionality as well as customizations to incorporate custom business rules and functionalities that require apex code incorporation into the Salesforce platform.
Greytrix has some unique solutions for Cloud CRM such as Salesforce Sage integration for Sage X3, Sage 100 and Sage 300 (Sage Accpac). We also offer best-in-class Cloud CRM Salesforce customization and development services along with services such as Salesforce Data Migration, Integrated App development, Custom App development and Technical Support business partners and end users. Salesforce Cloud CRM integration offered by Greytrix works with Lightning web components and supports standard opportunity workflow. Greytrix GUMU™ integration for Sage ERP – Salesforce is a 5-star rated app listed on Salesforce AppExchange.
The GUMU™ Cloud framework by Greytrix forms the backbone of cloud integrations that are managed in real-time for processing and execution of application programs at the click of a button.
For more information on our Salesforce products and services, contact us at [email protected]. We will be glad to assist you.