Apex Stub API Is Now Generally Available

Apex provides a stub API for implementing a mocking framework. 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. You can use the stub API to build your own mocking framework, or you can use one built by someone else.

You can define the behavior of stub objects, which are created at runtime as anonymous subclasses of Apex classes. The stub API comprises the System.StubProvider interface and the System.Test.createStub() method.

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

This GA version resolves the following limitations that were present in the pilot version of the stub API.

  • When calling the createStub() method in the pilot version, your Apex class was required to have a constructor that took zero arguments. This limitation is no longer present in the GA version.
  • You can now mock exceptions.
  • You can now mock classes that implement the Schedulable and Queueable interfaces.