How do you test asynchronous Apex and callouts?
Your confidence:Not rated
Model answer
- Boundaries: enqueue or start the async work between
Test.startTest()andTest.stopTest(). AtstopTest(), future methods, the queueable (first job only) and the batch (oneexecute) run synchronously. - Callouts:
Test.setMock(HttpCalloutMock.class, mock)(orWebServiceMockfor SOAP). Write mocks for success, error responses and timeouts. - Batch: keep test data within one scope; call
Database.executeBatch(new MyBatch(), 200). - Chained queueables: only the first job runs. Test each step's
executedirectly, and test the chaining decision separately (for example, assert thatLimits.getQueueableJobs()increased). - Finalizers: call the finalizer's logic through a testable method, or inject a failing dependency so the finalizer path runs.
- Scheduled Apex: schedule with a cron in the test, then assert the job record (
CronTrigger) and thatexecutestarts the batch. - Assert outcomes: records updated, logs written, events published (
Test.getEventBus().deliver()for platform events).
โ Key points to hit
โ Red-flag answers
- Real callouts in tests
- Asserting nothing after stopTest
- Expecting a whole chain to run in a test
โช Follow-ups
How do you test a timeout?
Have the mock throw a CalloutException (or return an error status), then assert the code logs the failure and schedules a retry.
How do you test platform event subscribers?
Publish the event in the test, call Test.getEventBus().deliver() to deliver it to subscribers, then assert the subscriber's effects.