PHPUnit - MockBuilder::enableProxyingToOriginalMethods() breaks when original constructor calls public method

给你一囗甜甜゛ 提交于 2019-12-24 22:35:59

问题


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

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.

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


回答1:


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.



来源:https://stackoverflow.com/questions/58096365/phpunit-mockbuilderenableproxyingtooriginalmethods-breaks-when-original-co

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