PHPUnit mock - call parent __get/__set/__isset

痞子三分冷 提交于 2019-12-11 06:07:23

问题


I am trying to mock a class that has inherited magic methods, but they are not getting implemented, and I have no idea how to fix it. Here's the code:

<?php
use PHPUnit\Framework\TestCase;

class AnnoyingTestCase extends TestCase
{
    public function testNoAttributes()
    {
        $mock = $this->createMock(Child::class);
        $mock->attribute = 'value';

        $this->assertEquals($mock->attribute, null);
    }
}

class Base
{
    private $attributes = [];

    public function __set($name, $value)
    {
        $this->attributes[$name] = $value;
    }

    public function __get($name)
    {
        return $this->attributes[$name] ?? null;
    }

    public function __isset($name)
    {
        return isset($this->attributes[$name]);
    }
}

class Child extends Base
{
}

I would expect the $mock->attribute to have the value I assigned it, but it does not because __set is not being called.

If I try to use ->addMethods(['__get', '__set']), then it throws an exception: Trying to set mock method "__get" with addMethods(), but it exists in class "Child". Use onlyMethods() for methods that exist in the class.. And yet adding a var_dump inside the __set method shows that it is not being called.

What can I do so that it has these methods? Note that I am not looking to implement my own equivalent of these methods, I want the mock to have these original methods.


回答1:


Found a fix for this exact issue, but it may cause more harm than good. The following code works:

$mock = $this->getMockBuilder(Child::class)
    ->enableProxyingToOriginalMethods()
    ->getMock();

There is, however, the problem that this proxies ALL original method calls, and there is no way to narrow down the methods that you want to proxy. And the biggest - potentially broken constructor calls - is described here: PHPUnit - MockBuilder::enableProxyingToOriginalMethods() breaks when original constructor calls public method



来源:https://stackoverflow.com/questions/58095070/phpunit-mock-call-parent-get-set-isset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!