PHPUnit-当原始构造函数调用公共方法时,MockBuilder :: enableProxyingToOriginalMethods()中断 [英] PHPUnit - MockBuilder::enableProxyingToOriginalMethods() breaks when original constructor calls public method

查看:128
本文介绍了PHPUnit-当原始构造函数调用公共方法时,MockBuilder :: enableProxyingToOriginalMethods()中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个单元测试,其中涉及模拟一个类,该类的构造函数调用了几个公共方法.至少到目前为止,不能将所述公共方法设为私有.同一个类还具有我想保留的魔术方法(__get/__ set/__ isset),这就是为什么我诉诸使用enableProxyingToOriginalMethods()的原因-我发现没有办法仅启用这三个原始方法(来源: PHPUnit-调用父级__get/__ set/__ isset ). 这样可以使魔术方法起作用,但会破坏构造函数.

I'm trying to write a unit test that involves mocking a class whose constructor calls several public methods. Said public methods cannot be made private, at least for now. The same class also has magic methods that I want to keep unmocked (__get/__set/__isset), which is why I resorted to using enableProxyingToOriginalMethods() - I found no way to enable just those three original methods (source here: PHPUnit - call parent __get/__set/__isset). This makes the magic methods work, however it breaks the constructor.

以下代码演示了该问题:

The following code demonstrates the problem:

<?php
use PHPUnit\Framework\TestCase;

class ExceptionTestCase extends TestCase
{
    public function testException()
    {
        $this->expectException(TypeError::class);
        $this->expectExceptionMessage('call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object');
        $this->getMockBuilder(Foo::class)
            ->enableProxyingToOriginalMethods()
            ->getMock();
    }
}

class Foo
{
    public function __construct()
    {
        $this->setBar();
    }

    public function setBar()
    {
    }
}

我希望这会起作用,因为这里绝对没有异常,但是它没有明显的原因破裂. 如果将public方法的可见性设置为private,那么它将按预期工作,但是我无法在实际代码中做到这一点.

I would expect this to just work, since there is absolutely nothing out of the ordinary here, and yet it breaks for no apparent reason. If the public method's visibility is set to private, then it works as expected, but I cannot do that in the real code.

如何在不触及上述公共方法的情况下解决此错误?我是否缺少一些MockBuilder配置?

How to fix this error without touching said public methods? Am I missing some MockBuilder config?

推荐答案

Test Proxies, which is what enableProxyingToOriginalMethods() relates to, solve a problem that is probably not yours. And for solving this problem, the constructor needs to be executed with all required arguments.

这篇关于PHPUnit-当原始构造函数调用公共方法时,MockBuilder :: enableProxyingToOriginalMethods()中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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