Level: AdvancedSalesforce

Apex Stub API for Mocking in Unit Tests Explained

Updated 9 min read
Apex Stub API featured image showing a test class swapping a real dependency for a fake

The Apex Stub API lets a test replace one class with a fake version, so the code under test runs without inserting records, querying the database or making a callout. You decide what each method returns, and the test runs in milliseconds.

This fills a real gap. A service class that calculates a fee from three other classes is hard to test honestly, because every test ends up building records for all three. The logic you care about gets buried under setup.

Apex Stub API diagram showing the call being intercepted by a stub provider

Caption: The calling code never knows it is talking to a stub, since the signature is unchanged.

What Is the Apex Stub API

The Apex Stub API is two pieces. A Test.createStub call that builds the fake, and a class implementing System.StubProvider that decides what the fake returns.

@IsTest
public class FeeServiceMock implements System.StubProvider {

    public Object handleMethodCall(
        Object stubbedObject,
        String stubbedMethodName,
        Type returnType,
        List<Type> paramTypes,
        List<String> paramNames,
        List<Object> args
    ) {
        if (stubbedMethodName == 'getFee') {
            return 4500;
        }
        if (stubbedMethodName == 'isOnline') {
            return true;
        }
        return null;
    }
}

The test then builds the Apex Stub API object and hands it to the code under test.

@IsTest
static void appliesDiscount() {
    FeeService fake = (FeeService) Test.createStub(
        FeeService.class,
        new FeeServiceMock()
    );

    EnrolmentCalculator calc = new EnrolmentCalculator(fake);
    Decimal total = calc.totalFor('a01xx');

    System.assertEquals(3825, total);
}

No records were created, no SOQL ran, and the test checks exactly one thing. That is the whole point of the Apex Stub API. That is what a unit test should look like.

What the Provider Receives

ArgumentWhat it holds
stubbedObjectThe stub itself
stubbedMethodNameThe method that was called
returnTypeWhat the real method returns
paramTypesThe parameter types, in order
paramNamesThe parameter names, in order
argsThe actual values passed in

The Apex Stub API passes an args list, and that is what makes a provider useful rather than fixed. You can return a different value per input, or record what was called so the test can assert on it afterwards.

if (stubbedMethodName == 'getFee') {
    String courseId = (String) args[0];
    return courseId == 'a01online' ? 3000 : 4500;
}

Why the Apex Stub API Matters

BenefitWhat it gives you
No DML in testsA suite that runs in seconds, not minutes
Real isolationA failure points at one class
No callout mocks neededA fake service class instead of a fake HTTP layer
Fewer limits usedTests stop hitting DML and SOQL ceilings
Honest coverageCoverage on logic rather than on setup code

The speed point compounds. A suite of 400 tests each inserting ten records can take twenty minutes, and a slow suite is a suite people skip. The post on testing triggers covers where real data is still the right choice.

The Rules You Have to Design Around

The Apex Stub API has firm limits, and they shape how you write your classes.

RuleWhat it means in practice
Only public and protected instance methods can be stubbedMake the dependency an instance, not a set of statics
Static methods cannot be stubbedA utility class of statics is untestable this way
Private methods cannot be stubbedTest them through the public surface
The class cannot be final, and nor can the methodLeave them open
System types cannot be stubbedWrap them in your own class
Only works inside a test contextA stub cannot be created at runtime
Constructors do not runAny setup in the constructor is skipped

That first rule is the important one. A class full of static methods cannot be stubbed at all, which is a strong argument for writing services as instances and passing them in.

Dependency Injection Makes It Possible

public with sharing class EnrolmentCalculator {

    private FeeService fees;

    public EnrolmentCalculator() {
        this(new FeeService());
    }

    public EnrolmentCalculator(FeeService fees) {
        this.fees = fees;
    }

    public Decimal totalFor(String courseId) {
        Decimal fee = fees.getFee(courseId);
        return fees.isOnline(courseId) ? fee * 0.85 : fee;
    }
}

Two constructors, and the Apex Stub API can reach everything. Writing services this way also keeps them bulk safe, which the post on bulkification covers. Production code uses the empty one, and the test passes a stub into the second. No framework, no configuration, six extra lines.

Apex Stub API vs Real Test Data

Apex Stub API and real test data comparison diagram

Caption: Both belong in a healthy suite, aimed at different things.

What you are testingPick
A calculation with several inputsStub the dependencies
A trigger firing on insertReal records
A validation ruleReal records
A service that calls three other servicesStub them
A SOQL query shapeReal records
Error handling when a dependency throwsStub, and throw from the provider
An end to end flow before releaseReal records

Throwing from a provider is the Apex Stub API case people forget. Mocking the HTTP layer instead is covered in the post on callout mocks. Testing what your code does when a dependency fails is almost impossible with real data and trivial with a stub.

if (stubbedMethodName == 'getFee') {
    throw new CalloutException('Service unavailable');
}

A Real Apex Stub API Example

The Apex Stub API cut our suite from minutes to seconds. Bright Path Tutors has an enrolment service that reads a fee, checks seat availability through a callout, and applies a discount rule. The original tests inserted courses, built an HTTP mock, and ran for nine seconds each.

ProblemWhat it cost
Records inserted per test14
An HTTP mock class to maintainExtra code nobody wanted to own
Nine seconds per testA suite nobody ran locally
Failures that pointed nowhereA broken validation rule failed 30 tests

We split the suite in two. Logic tests use stubs, and a small set of integration tests use real records.

MeasureBeforeAfter
Tests in the suite4661
Suite run time7 minutes95 seconds
Records inserted across the suite64048
Tests that failed on one rule change302

That last row is the real benefit. A failing test now tells you which class is wrong instead of telling you that something, somewhere, changed.

Recording Calls for Assertions

An Apex Stub API provider can keep a list of what it was asked, so a test can check that something was called.

public List<String> calls = new List<String>();

public Object handleMethodCall(Object o, String name, Type rt,
    List<Type> pt, List<String> pn, List<Object> args) {
    calls.add(name);
    return name == 'getFee' ? 4500 : null;
}

The test then asserts on the list, which is how you prove a cache was used or that a service was not called twice. This is the one capability a hand written fake class gives you less easily.

Common Mistakes with the Apex Stub API

MistakeWhat you seeFix
Static methods on the dependencyNothing can be stubbedMake the service an instance
Expecting the constructor to runNull fields inside the stubReturn values from the provider, not from state
A provider returning the wrong typeA cast error at runtimeMatch the declared return type exactly
One provider for every classA long if chain nobody can readOne provider per dependency
Stubbing everythingTests that pass while production failsKeep integration tests as well
Final class or methodA stub creation errorRemove the final keyword
Stubbing a system typeA compile or runtime failureWrap it in your own class first

Best Practices for the Apex Stub API

  • Write services as instances with a constructor that accepts dependencies
  • Keep one provider per dependency so each stays readable
  • Return values based on the args list rather than fixed constants
  • Use the provider to throw, so error paths get tested properly
  • Record calls when the test needs to prove something was invoked
  • Keep a small set of integration tests with real records alongside
  • Put providers in test classes or a test only class so they never ship as live code

Most Asked Apex Stub API Interview Questions

Q1: What does the Apex Stub API let you do?

Replace a class with a fake inside a test, so no records, queries or callouts are needed.

Q2: Which two pieces does it need?

A Test.createStub call and a class implementing the StubProvider interface.

Q3: What method does StubProvider require?

A handleMethodCall method that receives the call details and returns a value.

Q4: What arguments does that method receive?

The stub, the method name, the return type, the parameter types and names, and the actual arguments.

Q5: How do you return different values for different inputs?

Read the args list and branch on the values you find there.

Q6: Can you stub a static method?

No. Only public and protected instance methods can be stubbed.

Q7: Can you stub a private method?

No. Test it through the public surface instead.

Q8: Can a final class be stubbed?

No. Neither a final class nor a final method can be stubbed.

Q9: Can you stub a system type?

No. Wrap it in your own class and stub that.

Q10: Does the real constructor run?

No, which is why a provider should not rely on state set in the constructor.

Q11: Can you create a stub outside a test?

No. It works only in a test context.

Q12: Why does this push you toward dependency injection?

Because the dependency has to be an instance you can pass in, not a static call.

Q13: How many extra lines does that pattern cost?

Usually a second constructor and a field, so around six lines.

Q14: How do you test an error path with a stub?

Throw the exception from inside the provider for that method name.

Q15: Why is that hard with real data?

Because making a real dependency fail on demand is awkward and often impossible.

Q16: How do you assert that a method was called?

Record the method names in the provider and assert on that list.

Q17: Does using stubs remove the need for integration tests?

No. A suite of stubs can pass while the data layer is broken.

Q18: What does a stub do to test run time?

It removes DML and SOQL, which is usually where the time goes.

Q19: How does it compare with an HTTP callout mock?

A callout mock fakes the HTTP layer, while a stub fakes your own service class, which is simpler.

Q20: Where should provider classes live?

In test classes or a test only class, so they never deploy as live code.

Q21: Scenario: createStub throws an error on your class. What is the likely cause?

The class or the method is final, or the method is static or private.

Q22: Scenario: the stub returns a value and the code throws a cast error. Why?

The provider returned a type that does not match the declared return type.

Q23: Scenario: a provider has a 60 line if chain. What went wrong?

One provider is covering several dependencies. Split it.

Q24: Scenario: a utility class of statics needs testing. What now?

Either test it directly with real inputs, or refactor it into an instance service.

Q25: Does a stub count towards code coverage?

The code under test gets coverage, and the provider is test code.

Q26: Is this the same as Mockito in Java?

It is the platform building block such a framework would be built on, with less syntax sugar.

Q27: Can the args list be used to validate inputs?

Yes, and asserting on them is a good way to prove a method was called correctly.

Q28: What is the main design benefit of adopting it?

It pushes you toward small services with explicit dependencies, which are easier to change.

Q29: What is the one habit that makes stubs work?

Write every service as an instance and accept its dependencies in a constructor.

Q30: Can a stub be passed into a queueable or a batch class?

Yes, if the job accepts the dependency in its constructor, though the stub itself only exists inside the test.

Q31: How do you keep providers from growing out of hand?

Give each dependency its own provider and keep the branching to one switch on the method name.

Q32: What is a reasonable split between stub tests and data tests?

Most of the suite on stubs for logic, with a small set of data tests for triggers, rules and queries.

Official Resources

What Is Next

Next, read Apex Error Logging Framework Built Step by Step.