ApexSensei

Drills › Prove it with tests

Use a fake collaborator

Prove it with tests · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A notifier calls an outside gateway. Its unit tests must stay fast, offline and repeatable.

Replace an outside gateway with a test fake that records calls and can fail once on purpose.

What you will learn

extends makes your class a child; override replaces a parent method marked virtual. The Notifier accepts your fake anywhere it expects a Gateway.

public class FakeGateway extends Gateway {
    public override String send(String payload) {
        if (failNext) {
            failNext = false;
            throw new CalloutException('simulated');
        }
        return 'ACK:' + payload;
    }
}

Gotcha. A fake that always succeeds leaves the error path untested.

The task

Finish the fake gateway so tests can read what was sent, get a set reply, and force one failure.

Examples:

  • subject Login → ACK:CASE:Login
  • two deliveries → two payloads saved in order
  • failNext = true → the Notifier catches the error and returns RETRY

Requirements:

  1. Save every payload in sentPayloads, in call order, including an empty subject.
  2. Return ACK: plus the payload.
  3. When failNext is true, set it back to false and throw a CalloutException.
  4. Keep the class, its fields and send public. The Notifier and the checks use them directly.

Starter code

@IsTest
public class AS_CA2B6F4305F6_FakeGateway extends AS_CA2B6F4305F6_Gateway {
    public List<String> sentPayloads = new List<String>();
    public Boolean failNext = false;

    public override String send(String payload) {
        return null;
    }

    @IsTest
    static void capturesMessage() {
        AS_CA2B6F4305F6_FakeGateway fake = new AS_CA2B6F4305F6_FakeGateway();
        String result = AS_CA2B6F4305F6_Notifier.deliver(fake, 'Login');
        Assert.areEqual('ACK:CASE:Login', result);
        Assert.areEqual('CASE:Login', fake.sentPayloads[0]);
    }
}

When it passes

The fake saves payloads in order and returns ACK:<payload>. When failNext is set it fails once, the Notifier returns RETRY, and the next call works.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Prove bulk behavior · Mock an HTTP callout ›