PHPUnit模拟-调用父级__get/__ set/__ isset [英] PHPUnit mock - call parent __get/__set/__isset

查看:94
本文介绍了PHPUnit模拟-调用父级__get/__ set/__ isset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟一个继承了魔术方法的类,但是它们没有得到实现,而且我也不知道如何解决它. 这是代码:

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
{
}

我希望$mock->attribute具有我为其分配的值,但这不是因为没有调用__set.

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

如果我尝试使用->addMethods(['__get', '__set']),则会引发异常:Trying to set mock method "__get" with addMethods(), but it exists in class "Child". Use onlyMethods() for methods that exist in the class.. 但是在__set方法中添加var_dump表示未在调用它.

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.

推荐答案

找到了解决此确切问题的方法,但可能带来的弊大于利. 以下代码有效:

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();

但是,这存在一个问题,它可以代理所有原始方法,并且无法缩小您要代理的方法的范围.而最大的-可能破坏构造函数的调用-的描述如下: PHPUnit-当原始构造函数调用公共方法时,MockBuilder :: enableProxyingToOriginalMethods()中断

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

这篇关于PHPUnit模拟-调用父级__get/__ set/__ isset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆