More explicit stubbing of __call()
sebastianbergmann opened this issue · 2 comments
Lets assume we have a class C
with a __call()
method:
<?php declare(strict_types=1);
class C
{
public function __call(string $name, array $arguments)
{
switch ($name) {
case 'm':
return true;
}
}
}
One approach to stubbing the behaviour of C::m()
is
<?php declare(strict_types=1);
final class Test extends PHPUnit\Framework\TestCase
{
public function testOne(): void
{
$o = $this->createMock(C::class);
$o->method('__call')->willReturn(false);
$this->assertFalse($o->m());
}
}
Configuring __call
as shown above can become confusing and tedious when more than one "virtual" method needs to be stubbed and configured.
Another approach to stubbing the behaviour of C::m()
is
<?php declare(strict_types=1);
final class Test extends PHPUnit\Framework\TestCase
{
public function testTwo(): void
{
$o = $this->createPartialMock(C::class, ['m']);
$o->method('m')->willReturn(false);
$this->assertFalse($o->m());
}
}
The above works (at least in this simple case), and is more explict, but we do not want a partial stub here.
A better approach could be to provide a new method that works just like createMock()
but takes an array of additional methods as its second parameter.
This issue has been automatically marked as stale because it has not had activity within the last 60 days. It will be closed after 7 days if no further activity occurs. Thank you for your contributions.
Moved to sebastianbergmann/phpunit#3121.