Apex testing: data factories, async tests, mocks and meaningful assertions
Writing tests that prove behaviour: test data factories, @TestSetup, bulk and permission tests, testing async code, callout mocks and the Stub API.
Simple explanation
Deployment needs 75% code coverage across the org and every trigger covered. That's the floor. Good tests prove behaviour under realistic conditions.
Building blocks
- Test data factory: one class that creates valid records with sensible defaults, so tests don't break when a required field is added.
@TestSetup: create shared data once per test class.- Bulk tests: insert or update 200+ records to prove bulk safety.
- Permission tests:
System.runAs(user)with a user who has only the intended permission sets, to prove sharing and FLS behaviour. - Async tests: code between
Test.startTest()andTest.stopTest()gets fresh limits, and async jobs (future, queueable, the batch's singleexecute) run atstopTest(). - Callouts:
Test.setMock(HttpCalloutMock.class, new MyMock()); no real callouts in tests. - Stub API:
Test.createStubto mock dependencies behind interfaces, for fast unit tests without DML. - Assertions: use the
Assertclass (Assert.areEqual,Assert.isTrue) with messages that explain intent.
Real-world analogy
Coverage is counting how many rooms a fire inspector walked through. Assertions are checking that the smoke alarms in those rooms actually work. An inspector who walks through every room without testing anything gives you 100% coverage and no safety.
Worked example
@IsTest
private class ErpOrderSubmissionJobTest {
@TestSetup
static void setup() {
Account acc = TestDataFactory.account(new Map<String, Object>{ 'ERP_Customer_Id__c' => 'C-100' });
insert acc;
insert TestDataFactory.opportunities(acc.Id, 200); // bulk
}
private class ErpSuccessMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(201);
res.setBody('{"status":"accepted"}');
return res;
}
}
@IsTest
static void closedWonEnqueuesOneJobAndSubmits() {
Test.setMock(HttpCalloutMock.class, new ErpSuccessMock());
List<Opportunity> opps = [SELECT Id FROM Opportunity];
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
Test.startTest();
update opps;
Assert.areEqual(1, Limits.getQueueableJobs(), 'One job for the whole chunk, not one per record');
Test.stopTest(); // the queueable runs here
Assert.areEqual(200, [SELECT COUNT() FROM Opportunity WHERE ERP_Status__c = 'Submitted'],
'Every won opportunity should be marked as submitted');
}
}
Diagram
Key points
- 75% org-wide coverage is the minimum; assert behaviour.
- Test data factory +
@TestSetup; never rely on org data (SeeAllData=false). - Test bulk (200+), negative paths and different users with
System.runAs. Test.startTest/stopTestgives fresh limits and runs async work.HttpCalloutMockfor callouts; Stub API for isolated unit tests.- Use the
Assertclass with clear messages.
Limits and gotchas
- Only one batch
executeruns in a test, and chained queueables don't run beyond the first. SeeAllData=truemakes tests depend on org data and break between sandboxes. Avoid it (a few objects, such as some standard price book cases, need special handling:Test.getStandardPricebookId()).- Tests that pass by catching every exception prove nothing.
- Large test suites slow deployments. Keep unit tests fast with mocks; keep a smaller set of integration-style tests with DML.
π€ How to say this in an interview
Interviewers probe whether you test bulk, security and async behaviour, not just coverage. Describe your factory, one async test, and how you mock callouts. Mention running tests in CI on every pull request.
Common follow-ups
How do you test code that behaves differently for different users?
Create users with specific profiles and permission sets in the test, then run the code inside System.runAs(user) and assert what each user can see or do. Combine with user-mode queries so FLS and sharing are enforced in the code under test.
How do you keep tests fast in a large org?
Mock dependencies with interfaces and the Stub API, avoid unnecessary DML, use @TestSetup for shared data, and run the full suite in CI while developers run focused tests locally.