<?php
use PHPUnit\Framework\TestCase;
/**
* This code snippet shows how to create spies
* with PHPUnit's mock object as shown by
*
* Anna Filina - https://twitter.com/afilina
* in her video
* https://www.youtube.com/watch?v=_LeCyU1X5bY
*/
class SpyPhpUnitTest extends TestCase
{
public function testSpyOnBar() : void
{
$bar = $this->getMockBuilder(Bar::class)
->enableProxyingToOriginalMethods()
->getMock();
// Creating spies
$bar->expects($spy1 = self::any())
->method('first');
$bar->expects($spy2 = self::any())
->method('second');
$val = (new Foo())->doStuff($bar);
self::assertSame(1, $val);
self::assertSame(1, $spy1->getInvocationCount());
$invocation = $spy1->getInvocations()[0];
self::assertSame([1], $invocation->getParameters());
self::assertSame(0, $spy2->getInvocationCount());
}
}
class Foo
{
public function doStuff(Bar $bar) : int
{
return $bar->first(1);
}
}
class Bar
{
public function first(int $val) : int
{
return $val;
}
public function second() : int
{
return 2;
}
}
Result
Time: 00:00.007, Memory: 18.00 MB
There was 1 error:
1) SpyPhpUnitTest::testSpyOnBar
Call to undefined method PHPUnit\Framework\MockObject\Rule\AnyInvokedCount::getInvocations()
PhpunitExec.php:21
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.