Build a Mocking Framework with the Apex Stub API (Pilot)

Apex now provides a stub API for implementing your own mocking framework. You can define the behavior of stub objects, which are created at runtime as anonymous subclasses of Apex classes. The stub API is composed of the System.StubProvider interface and the System.Test.createStub() method.
Note

Note

We provide the Apex stub API to selected customers through a pilot program that requires agreement to specific terms and conditions. The Apex stub API is subject to change and isn’t generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements. We can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

A mocking framework has many benefits. It can streamline and improve testing and help you create faster, more reliable tests. You can use it to test classes in isolation, which is important for unit testing. Building your mocking framework with the stub API can also be beneficial because stub objects are generated at runtime. Because these objects are generated dynamically, you don’t have to package and deploy test classes.

To use a stub version of an Apex class:
  • Define the behavior of the stub class by implementing the System.StubProvider interface.
  • Instantiate a stub object by using the System.Test.createStub() method.
  • Invoke the relevant method of the stub object from within a test class.
Note

Note

This feature is intended for advanced Apex developers. Using it requires a thorough understanding of unit testing and mocking frameworks. If you think that a mocking framework is something that makes fun of you, you might want to do a little more research before reading further.