Mock the Base Apex Class in Tests
When writing unit tests for an extension provider class, sometimes we want to mock the super()
method in the extension provider class. However, the Apex test framework does not support mocking objects or methods in a namespace that is different from where test classes are defined. This tutorial provides a workaround to allow us to mock super()
in the extension provider class. To learn more about Apex’s namespace, refer to Default Namespaces in Apex on the Salesforce Developers blog.
The idea is to separate the logic for calling the super()
default logic so that it can be mocked in the test.
Let’s walk through an example for testing the extension provider class.
Assume we have an extension provider class called Custom_Inventory
that extends a Base Apex class CommerceDxSampleapp.CommerceDx_Inventory
.
The Base Apex Class has its own namespace and is different from the org of the extension provider class.
The base Apex class looks like this:
The Custom_Inventory
class belongs to current org's namespace._
To create an extension provider, add a class that extends the base Apex class:
To make sure that we can mock the default logic, add a method that only calls super()
and make it overridable by marking it as virtual
. We also need to mark the class as virtual
.
Next, define the test class. (See Salesforce Developers to learn how to write an Apex test.)
Finally, define an inner mock class called Fake_Custom_Inventory
to override the logic for the super()
method that belongs to the base Apex class. Then the test method can use the mock class to return the expected result for the super()
logic.