Apex Testing Stub API and why namespace limits matter
Salesforce has the Apex Testing Stub API, which allows stubbing of Apex types. Using Test.createStub with a StubProvider, developers can replace dependencies in tests and control execution paths without calling the actual implementations.
🔗 Reference: https://lnkd.in/g-nYTctt
The major limitation is simple:
Apex stubs only work within the same namespace. 😭
That means subscriber orgs cannot stub managed package classes. Even if a managed package exposes a global StubProvider, Test.createStub still requires the stubbed type to be in the test's namespace.
Real scenario: 🧐
Your subscriber org code uses methods from a managed package class that sometimes returns an error payload instead of throwing an exception.
The subscriber may have error handling for that case, but there is no way to force the managed package to return that error in a test. That path is effectively untestable.
If StubProvider worked across namespaces, subscriber tests could simulate managed package behavior beyond generic callout failures and exceptions.
Would it be possible for Salesforce to remove the current namespace constraints to make unit testing more powerful in multi-package environments?
Until that happens, the burden is on package providers. Exposing explicit test hooks, global flags like "isTestMode" or "forceError", or documented failure modes would go a long way toward making it testable in subscriber orgs.
