Trustworthy code that talks to the world
Strong tests prove behaviour in bulk and under different users; secure integrations use Named Credentials, clear error handling and the right pattern for each use case.
- TestingTest data, startTest, bulk and assertions.
- CalloutsNamed Credentials and mocks.
- IntegrationREST services, Platform Events and CDC.
You cannot deploy Apex to production without tests, and almost every org integrates with outside systems. This set covers writing meaningful tests (not just coverage) and the integration patterns interviewers ask about most.
1. What makes a good Apex test class?
It creates its own data (tests do not see org data by default), tests positive, negative and bulk scenarios (200+ records), asserts outcomes with clear messages, runs as different users where security matters, and stays independent of other tests. Coverage of 75% is the deployment minimum — assertions are what make tests valuable.
@IsTest
private class OpportunityServiceTest {
@TestSetup
static void makeData() {
Account a = new Account(Name = 'Test Co');
insert a;
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(Name = 'Opp ' + i, AccountId = a.Id, StageName = 'Prospecting', CloseDate = Date.today()));
}
insert opps;
}
@IsTest
static void closesAllAsLostInBulk() {
Set<Id> ids = new Map<Id, Opportunity>([SELECT Id FROM Opportunity]).keySet();
Test.startTest();
OpportunityService.closeAsLost(ids, 'Budget');
Test.stopTest();
Assert.areEqual(200, [SELECT COUNT() FROM Opportunity WHERE StageName = 'Closed Lost'], 'All 200 should be closed lost');
}
}2. What do Test.startTest() and Test.stopTest() do?
Code between them gets a fresh set of governor limits, separating setup from the code under test. stopTest() also forces asynchronous work started inside the block (future, queueable, batch, scheduled) to run synchronously, so you can assert its results right after.
3. How do you test HTTP callouts?
Tests cannot make real callouts. Implement HttpCalloutMock to return a fake response and register it with Test.setMock. Test success and error responses.
@IsTest
private class RateClientTest {
private class RateMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"rate": 83.2}');
return res;
}
}
@IsTest
static void returnsRate() {
Test.setMock(HttpCalloutMock.class, new RateMock());
Test.startTest();
Decimal rate = RateClient.usdToInr();
Test.stopTest();
Assert.areEqual(83.2, rate);
}
}4. How do you make a callout securely?
Use a Named Credential (with an External Credential for the authentication) instead of hard-coding URLs, tokens or passwords. Reference it as callout:My_Credential/path; Salesforce adds authentication headers and manages token refresh. Always set a timeout and handle non-200 responses.
public with sharing class RateClient {
public static Decimal usdToInr() {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Rates_API/v1/latest?base=USD&symbols=INR');
req.setMethod('GET');
req.setTimeout(10000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Rates API returned ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (Decimal) body.get('rate');
}
}5. How do you expose a custom REST API from Salesforce?
Annotate a global class with @RestResource(urlMapping=...) and methods with @HttpGet, @HttpPost and so on. External systems call it at /services/apexrest/... with an OAuth token from a connected app (or an External Client App). Validate input and return clear error codes.
@RestResource(urlMapping='/orders/*')
global with sharing class OrderApi {
@HttpGet
global static Order__c getOrder() {
String orderNo = RestContext.request.requestURI.substringAfterLast('/');
List<Order__c> rows = [SELECT Id, Name, Status__c, Total__c FROM Order__c WHERE Name = :orderNo WITH USER_MODE LIMIT 1];
if (rows.isEmpty()) {
RestContext.response.statusCode = 404;
return null;
}
return rows[0];
}
}6. What are Platform Events and when do you use them?
Platform Events are an event bus for publish/subscribe integration: Apex, Flow or external systems publish an event; triggers, flows, LWC (via empApi) or external subscribers react. Use them to decouple systems, notify in near real time and handle work after commit (with “publish after commit”).
Order_Shipped__e evt = new Order_Shipped__e(Order_Number__c = 'LF-1042', Carrier__c = 'BlueDart');
Database.SaveResult sr = EventBus.publish(evt);
trigger OrderShippedSubscriber on Order_Shipped__e (after insert) {
// notify customer, update order status, etc.
}7. Which integration patterns should you know?
- Request–reply — Salesforce calls an API and waits (synchronous callout).
- Fire and forget — publish a Platform Event or queue a callout asynchronously.
- Batch data sync — scheduled bulk loads with the Bulk API or ETL tools.
- Remote call-in — external systems call Salesforce REST/SOAP APIs.
- UI update on data change — Change Data Capture or Platform Events streamed to the UI.
8. What is Change Data Capture?
CDC publishes events automatically when records of selected objects are created, updated, deleted or undeleted, including changed fields. External systems subscribe to keep their copies in sync without polling. Apex triggers on change events can also process them asynchronously.
Remember
Key points
- Assertions over coverage
75% is the floor, not the goal.
- stopTest() runs async
Assert async results right after.
- Named Credentials
No secrets in code.
- Events decouple systems
Publish/subscribe instead of tight calls.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 What does @IsTest(SeeAllData=true) do and why avoid it? Basic
It lets tests see org data, making them depend on data that may change or not exist in other orgs. Create test data instead.
-
2 How do you test code as a specific user? Intermediate
Create a test user with the right profile or permission sets and wrap code in
System.runAs(user). -
3 What is a test data factory? Basic
A reusable @IsTest class with methods that create valid records, so tests stay short and consistent when required fields change.
-
4 How do you test a batch class? Intermediate
Create data, call
Database.executeBatchbetween startTest and stopTest (only one execute chunk runs in tests), then assert results. -
5 SOAP vs REST in Salesforce integrations? Intermediate
REST is lightweight JSON over HTTP — the default for most integrations and mobile apps. SOAP uses XML with a strict WSDL contract, still common with older enterprise systems.
-
6 How do you handle an external system that is temporarily down? Advanced
Make the callout asynchronous, log failures, retry with back-off (Queueable with a finalizer or a scheduled retry job), and alert after repeated failures.