Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example we are going to mock and test a non existent class methods which produce errors below. We will test setex and exists methods of Predis\ClientInterface interface. They actually exists but not in a traditional way.


Error


Expectation failed for method name is equal to <string:setex> when invoked 1 time(s)
Trying to configure method "setex" which cannot be configured because it does not exist, has not been specified, is final, or is static.

Expectation failed for method name is equal to <string:exists> when invoked 1 time(s)
Trying to configure method "exists" which cannot be configured because it does not exist, has not been specified, is final, or is static.

CacheUtil


declare(strict_types=1);

namespace AppBundle\Util;

use Predis\ClientInterface;

class CacheUtil
{
private $cache;

public function __construct(ClientInterface $cache)
{
$this->cache = $cache;
}

public function cache(string $id, string $value): void
{
$this->cache->setex($id, 3600, $value);
}

public function exists(string $id): int
{
return $this->cache->exists($id);
}
}

CacheUtilTest


declare(strict_types=1);

namespace Tests\AppBundle\Util;

use AppBundle\Util\CacheUtil;
use PHPUnit\Framework\TestCase;
use PHPUnit_Framework_MockObject_MockObject;
use Predis\ClientInterface;

class CacheUtilTest extends TestCase
{
/** @var ClientInterface|PHPUnit_Framework_MockObject_MockObject */
private $cacheMock;
/** @var CacheUtil */
private $cacheUtil;

protected function setUp()
{
$this->cacheMock = $this
->getMockBuilder(ClientInterface::class)
->setMethods(['setex', 'exists'])
->disableOriginalConstructor()
->getMockForAbstractClass();

$this->cacheUtil = new CacheUtil($this->cacheMock);
}

/**
* @test
*/
public function it_caches()
{
$id = 'ID';
$value = 'VALUE';

$this->cacheMock
->expects($this->once())
->method('setex')
->with($id, 3600, $value)
->willReturn(true);

$this->assertNull($this->cacheUtil->cache($id, $value));
}

/**
* @test
*
* @dataProvider getCacheExistenceProvider
*/
public function it_checks_cache_existence($existence)
{
$id = 'ID';

$this->cacheMock
->expects($this->once())
->method('exists')
->with($id)
->willReturn($existence);

$this->assertSame($existence, $this->cacheUtil->exists($id));
}

public function getCacheExistenceProvider()
{
return [[0], [1]];
}
}

Result


$ vendor/bin/phpunit --filter CacheUtilTest tests/AppBundle/Util/CacheUtilTest.php
PHPUnit 6.3.1 by Sebastian Bergmann and contributors.

... 3 / 3 (100%)

Time: 61 ms, Memory: 4.00MB

OK (3 tests, 6 assertions)