CodeIgniter Forums
Mocking to be allowed for all services - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Feature Requests (https://forum.codeigniter.com/forum-29.html)
+--- Thread: Mocking to be allowed for all services (/thread-78985.html)



Mocking to be allowed for all services - gmeister2 - 04-05-2021

Context
There are 2 helpers to load a service:
  • $example = service('example');
  • $example = single_service('example');
Only the first will let you use the following when testing:
Services::injectMock('example', $example);

This is not clear in the documentation, I assumed mocking would work for all services:
Testing / Getting Started / Mocking Services

Feature Request:
The framework looks for all service mocks instigated, either for:
  • a shared instance (e.g. service('example'))
    or
  • a non-shared instance (e.g. single_service('example'))
My current (user-side) solution:
in app/Config/Services.php

PHP Code:
public static function example(bool $getShared true)
{
    if ($getShared)
    {
        return static::getSharedInstance('example');
    }
    elseif (isset(static::$mocks['example']))
    {
        return static::$mocks['example'];
    }

    return new Example();