在PHPUnit中进行模拟时在回调中通过引用传递 [英] Pass by reference in a callback when mocking in PHPUnit

查看:79
本文介绍了在PHPUnit中进行模拟时在回调中通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要模拟的接口,并模拟其中一种方法的行为.

I have an interface I want to mock, and mock the behaviour of one of it's methods.

所以我创建了一个回调,可以非常简单地模拟行为.

So I have created a callback that mocks the behaviour very simply.

如果我创建一个基于此接口的新对象,则此测试通过,但是我想模拟该接口.

This test passes if I create a new object that is based on this interface, but I would like to mock the interface.

被模拟的setUp方法被很好地调用,并且在我的回调中调用getVar('testing')返回该值.但是我的断言失败了,因为该值不可用.

The mocked setUp method is being called fine, and calling getVar('testing') in my callback returns the value. However my assertion fails, because that value isn't available.

似乎您无法在PHPUnit中做到这一点?除非我很笨.

It seems that you can't do this in PHPUnit? Unless I am being stupid.

代码流的简要说明; "getVar"中的代码调用一个方法,该方法在添加的插件上调用"setUp".当它调用"setUp"时,它将传入"$ this".我希望这个$ this可以通过引用传递,并且可以与真实"对象一起使用.

Brief explanation of the code flow; The code in "getVar" calls a method which calls the "setUp" on the added plugin. When it calls "setUp" it passes in "$this". It is $this I am expecting to be passed by reference and which works with a "real" object.

class DefaultRendererTest extends \PHPUnit_Framework_TestCase
{

    public function testSetGetVar()
    {
        $theme = $this->getMock('ThemeInterface');

        $plugin = $this->getMock('PluginInterface');
        $plugin->expects($this->once())
          ->method('setUp')
          ->will($this->returnCallback(function($r){

              $r->setVar('testing', "fooBar");

        }));

        $renderer = new DefaultRenderer($theme, null);
        $renderer->addPlugin($plugin);
        $this->assertEquals('fooBar',$renderer->getVar('testing'));
    }
}

有关此接口的信息,DefaultRenderer实现了RendererInterface

For info here is the interface, the DefaultRenderer implements a RendererInterface

interface PluginInterface
{
    function setUp(RendererInterface $renderer);
}

推荐答案

好的,出于兴趣,我找到了问题所在.似乎在实际调用发生之前,PHPUnit会自动克隆参数.我看不出这样做的真正原因,但也许有一个原因.看一下Framework/MockObject/Invocation/Static.php,只有一种方法可以避免这种情况(基于内置的模拟代码):在DefaultRenderer中实现私有的__clone()方法.

OK, out of interest, I tracked down the issue. It seems that PHPUnit automatically clones the parameters before the actual invocation takes place. I don't see a real reason for this, but maybe there is one. Taking a look at Framework/MockObject/Invocation/Static.php, there is only a single way how you can avoid this (on basis of the built in mock code): Implement a private __clone() method in the DefaultRenderer.

我还建议您在IRC或PHPUnit邮件列表上询问有关此行为或模拟对象库的信息.

I'd also suggest you ask on IRC or the PHPUnit mailinglist about this behaviour or the mock object library.

这篇关于在PHPUnit中进行模拟时在回调中通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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