Using the Apex Stub API with mocking frameworks

Implementing mock classes for small code bases, or as an aid to get a better understanding of the concept of unit testing, as we have done in this chapter, is fine. However, it can quickly become onerous and a maintenance overhead for larger code bases. The Apex Stub API was designed to handle any class shape for a reason.

The stubbedObject parameter can be used to determine to what type the method being called belongs. This allows for the creation of a single System.StubProvider implementation that can implement more advanced services that can be leveraged by unit tests without the need to write their own mock classes over and over. The playback of preconfigured responses to mocked methods and the recording of each method call it receives for later assertion is an example of this.

The concept of a mocking framework is not new. There are many well-established frameworks, such as the popular Mockito framework for Java or Jasmine for JavaScript/Node.js applications. However, mocking is a relatively new concept and capability in Apex, so there is an opportunity for building Apex-based mocking frameworks.

FinancialForce.com has published an open source mocking framework known as ApexMocks. While it predates the arrival of the Apex Stub API, it has been updated to work with this API. The advantage is that the code generator used to create the mock classes for use with Apex Mocks is no longer required, nor is the explicit use of Apex interfaces.

In the remainder of this chapter, we will review the benefits of a mocking framework through the use of the ApexMocks framework (now included in the sample code of this chapter). We'll apply it first to our sample Car class model and then to unit test scenarios from the FormulaForce application. A full walk-through is worthy of an entire book in my view. You can read more about ApexMocks through the various blog and documentation links on its README file: https://github.com/financialforcedev/fflib-apex-mocks/blob/master/README.md.

Credit should be given to Paul Hardaker for the original conception and creation of ApexMocks. As an experienced Java developer coming to the platform and used to using Mockito, he was quickly driven to find out whether a similar unit testing facility could be created on the platform. Thus, ApexMocks inherits much of its API design from Mockito. Since then, the framework has gone from strength to strength and received several other submissions and support from the community, including presentations at Dreamforce. Much of what I know about the area of unit testing is also due to Paul's tutoring. Thank you!

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

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