Suppose I want to mock the API in unit tests for my extension, can I do that? Or should I implement an interface myself that is just a wrapper around civicrm_api3, and create mocks of that interface?

Thank you!


update: I think a part of the answer is here in the source: https://github.com/civicrm/civicrm-core/tree/master/Civi/API/Provider

  • I'm not sure it could be used to mock the Civi API, but there is hook_civicrm_apiWrappers(). Whether it "wraps" each API request or the API itself is unclear to me. I'd think your extension would have to instantiate an API object to make it mockable? Where most CiviCRM code calls civicrm_api3() to interact with the API. I'm interested to see how you achieve this! Commented Oct 7, 2016 at 1:38

2 Answers 2


Generally, you need to get a reference to the API kernel. (For testing, I usually build up a custom instance, but you can use Civi::service("civi_api_kernel")). Then call registerApiProvider(...) and pass along a new provider. I usually define mock APIs using new AdhocProvider(...).

There are examples of mocking an API in api_v3_UtilsTest and CRM_Core_ManagedEntitiesTest.

(Update) I originally thought api_v3_UtilsTest was easier to read, but maybe CRM_Core_ManagedEntitiesTest is easier to generalize/imitate. Note how the setup() registers the API provider:

$this->apiKernel = \Civi::service('civi_api_kernel');
$this->adhocProvider = new \Civi\API\Provider\AdhocProvider(3, 'CustomSearch');

and how testRemoveDeclaration_CleanupUnused() manipulates the CustomSearch.getrefcount API to return different values at different times, e.g.:

// Override 'getrefcount' ==> The refcount is 1
$this->adhocProvider->addAction('getrefcount', 'access CiviCRM', function ($apiRequest) {
  return civicrm_api3_create_success(array(
      'name' => 'mock',
      'type' => 'mock',
      'count' => 1,
  • This is super useful. I've mocked the API myself before by creating a configurable wrapper service container for my code. I'm new to the Civi namespaced stuff, and CiviCRM's own container system, looks a good direction and will try to grok the code when I get a chance. thanks. Commented Nov 29, 2016 at 10:17

Maybe I'm misunderstanding the question but do you mean this? https://wiki.civicrm.org/confluence/display/CRMDOC/Testing#Testing-PHPunittests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.