Testing Advanced Scenarios in Apex

Share

Mocking Callouts

Why Callout Mocking Is Required

Salesforce does not allow real HTTP callouts in tests.
Instead, you must mock the external response.

Simple Explanation

In tests, Salesforce says: “Don’t call the real internet—pretend it replied.”


Real-Life Example

Testing a payment API without charging a real credit card.


HttpCalloutMock Example

@isTest
global class PaymentMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HttpResponse();
        res.setStatusCode(200);
        res.setBody('{"status":"success"}');
        return res;
    }
}
@isTest
static void testCallout() {
    Test.setMock(HttpCalloutMock.class, new PaymentMock());
    Test.startTest();
    MyCalloutService.makeCallout();
    Test.stopTest();
}

Gist (Quick Revision)

Mock callouts simulate external APIs so tests run safely and reliably.


Testing Async Apex (Future, Queueable, Batch)

Why Async Testing Is Special

Async Apex runs after the main transaction, so tests must wait for it.

Simple Explanation

Async code is like a background job—you must wait until it finishes.


Testing Future / Queueable Apex

@isTest
static void testQueueable() {
    Test.startTest();
    System.enqueueJob(new MyQueueableJob());
    Test.stopTest(); // waits for async job
}

Testing Batch Apex

@isTest
static void testBatch() {
    Test.startTest();
    Database.executeBatch(new MyBatchClass(), 200);
    Test.stopTest();
}

Gist (Quick Revision)

Always use Test.startTest() and Test.stopTest() for async testing.


Test Data Patterns (Professional Approach)

Pattern 1: Use @testSetup for Shared Data

@testSetup
static void setupData() {
    insert new Account(Name = 'Shared Account');
}

Pattern 2: Factory Method for Test Data

public class TestDataFactory {
    public static Account createAccount() {
        return new Account(Name = 'Test Acc');
    }
}

Pattern 3: Create Only What You Need

Avoid unnecessary records—keep tests fast and focused.


Real-Life Example

Don’t create a full company database just to test one method.


Gist (Quick Revision)

Good test data is minimal, reusable, and intentional.


Common Testing Mistakes (Avoid These)

❌ Mistake 1: No Assertions

// Test passes but checks nothing

❌ Mistake 2: Testing Only Happy Paths

Always test failure scenarios too.


❌ Mistake 3: Depending on Existing Data

Never rely on org data—tests must be self-contained.


❌ Mistake 4: Chasing Coverage Only

High coverage ≠ good tests.


Correct Mindset

Test behavior, not lines of code.


Gist (Quick Revision)

Avoid empty tests, org data dependency, and coverage-only thinking.

  • January 6, 2026