vendredi 24 novembre 2017

How to test that a PHP Closure passed as a parameter to a function has been called exact number of times

I am trying to find a way to check that Closure function passed to a method in my unit test has been called exactly one time. But Closure class in PHP is declared as final and I get the following error message when I run it : "Class "Closure" is declared "final" and cannot be mocked."

Here is a code example. I am trying to check that valueProducer() has been called exactly one time.

class PoorCache{
    protected $storage;

    /**
     * Returns value from cache and if the value lacks puts it into the cache storage
     * @param string $key
     * @param Closure $valueProducer produces a value for storage, i.e. makes a request to DB
     * @return mixed
     */
    public function remember($key, Closure $valueProducer)
    {
            if (array_key_exists($key, $this->storage))
            {
                    return $this->storage[$key];
            }

            $value = $this->storage[$key] = $valueProducer();
            return $value;
    }
}

class PoorCacheTest extends TestCase {
    public function testRemeber(){
        $mockedValueProducer = $this->getMock(\Closure::class);
        $mockedValueProducer->expects($this->once())->method('call');

        $cache = new PoorCache();
        $cache->remember('myKey', $mockedValueProducer);
        $cache->remember('myKey', $mockedValueProducer);
    }
}

Aucun commentaire:

Enregistrer un commentaire