Writing unit tests with the Apex Stub API

The Apex Stub API applies only within an Apex test context, so it cannot be used to implement DI outside of tests. To do that, you still need to leverage Apex interfaces. Utilizing Apex Stub APIs requires an understanding of the following:

  • Implementing the Stub Provider interface: The System.StubProvider system-provided Apex interface is effectively a callback style interface. It allows your mocking code to be informed when method calls are against classes you are mocking in your test. You can implement this interface multiple times, once per class you're mocking, or a single implementation for building sophisticated generalized mocking frameworks. The Apex Mocks open source framework from FinancialForce.com is one such framework that we will be reviewing later.
  • Dynamic creation of stubs for mocking: The platform automatically creates instances of classes you wish to mock through the Test.createStub method. You do not need to create Apex interfaces to perform DI when using the Stub API. The only requirement is that you provide the platform with an implementation of the Test.StubProvider interface to call back on when methods on the created stub instance are called during test execution.

In the following sub-sections, we will dig a little deeper into the preceding bullets with some simple sample code that is intended to help illustrate the key concepts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.174.76