APEX-Q09Design IntermediateApex & triggers#apex#async-apex#testing

How do you test asynchronous Apex and callouts?

Your confidence:Not rated

Model answer

  • Boundaries: enqueue or start the async work between Test.startTest() and Test.stopTest(). At stopTest(), future methods, the queueable (first job only) and the batch (one execute) run synchronously.
  • Callouts: Test.setMock(HttpCalloutMock.class, mock) (or WebServiceMock for 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 execute directly, and test the chaining decision separately (for example, assert that Limits.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 that execute starts 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.