lundi 12 juillet 2021

Why is the Reflection for Memcache::get() different from the doc?

I am trying to add unit tests to a class that uses Memcache as a service to get and store keys on the local memcached daemon.

My problem is that even though the code runs fine, when I try to mock the Memcache class and the get() method is called, I get this kind of error :

ArgumentCountError: Too few arguments to function Mock_Memcache_b25e34cb::get(), 1 passed in /path/to/file.php on line 64 and exactly 3 expected

I suspected a reflection error, so I tried a small script to test it out :

<?php
$class = new ReflectionClass(Memcache::class);
$getMethod = $class->getMethod('get');
$getParams = $getMethod->getParameters();
foreach($getParams as $param) {
    var_dump((string) $param);
}

The output I get is

string(35) "Parameter #0 [ $param0 ]"

string(36) "Parameter #1 [ &$param1 ]"

string(36) "Parameter #2 [ &$param2 ]"

However, the documentation found at the official PHP doc states that the signature should be :

Memcache::get(string $key, int &$flags = ?): string

or

Memcache::get(array $keys, array &$flags = ?): array

How can the discrepancy be explained? Why does my code run fine on production but fails on the UT? Is there a way for me to solve this problem other than creating my own mock class for Memcache? Thanks!

FYI, my current method to get the mock is this :

protected function createMock($originalClassName)
    {
        return $this->getMockBuilder($originalClassName)
                    ->disableOriginalConstructor()
                    ->disableOriginalClone()
                    ->disableArgumentCloning()
                    ->disallowMockingUnknownTypes()
                    ->getMock();
    }

public function existsReturnsTrueOrFalse($value, $expected)
    {
        $memcacheMock = $this->createMock(\Memcache::class);
...
    }




Aucun commentaire:

Enregistrer un commentaire