【问题标题】:How can I set the value of a protected var in a mock test (CakePHP)如何在模拟测试(CakePHP)中设置受保护变量的值
【发布时间】:2016-10-21 13:50:26
【问题描述】:

我想测试一个调用 API 的 Shell。 Shell 有一个函数可以为受保护的 var protected $_credential = []; 设置值

class ImportShell extends AppShell
{
    protected $_credential = [];

    public function sales() {
        $credential = $this->Credential->find('first', [
            'conditions' => [
                'Credential.id' => $this->args[0]
            ]
        ]);
        $this->_credential = $credential;
    }
}

它使用$this->args 中的值来查找表条目并将结果写入$_credential

当我这样使用 $_credential 时,如何在我的测试中访问/更改它?

$ImportShell = $this->getMockBuilder('ImportShell')
    ->setMethods(array('find'))
    ->getMock();

$ImportShell->sales();

我如何访问/更改$this->args

【问题讨论】:

    标签: cakephp mocking phpunit cakephp-2.6


    【解决方案1】:

    使用反射

    Reflections提供修改和查询代码的机制,对set a property value有特定的功能。语法有点笨拙,但这允许您修改类属性(和函数)的可访问性和值。这样的事情会做你想做的事:

    $class = new ReflectionClass("ImportShell");
    $property = $class->getProperty("_credential");
    $property->setAccessible(true);
    
    $ImportShell = $this->getMockBuilder('ImportShell')
        ->setMethods(array('find'))
        ->getMock();
    $ImportShell->_credential = ['stuff'];
    

    有一个插件

    Friends Of Cake Test Utilities plugin 简化了语法以实现相同的目的。使用这个插件的语法是:

    $this->setProtectedProperty('_credential', ['stuff'], $ImportShell);
    

    真的有必要吗?

    args is a public property。可以在调用测试函数之前简单地设置用于填充它的公共属性,而不是操作受保护的属性。

    $ImportShell = $this->getMockBuilder('ImportShell')
        ->setMethods(array('find'))
        ->getMock();
    
    $ImportShell->args = ['stuff'];
    $ImportShell->sales();
    

    尽管考虑到问题的表述方式,但模拟 Credential 模型并添加一个期望它会被调用并返回你想要的东西可能会更有意义。

    【讨论】:

    • 谢谢。虽然第一位不起作用。 FoC 插件适用于 cake 3(我使用 cakePhp 2.6)。但是我现在正在调用一个公共函数并按照您的描述在测试中传递参数
    • 第一个代码块是现成的代码(因此它可能包含错误,但原则上它应该是正确的)-“不起作用”没有帮助/清楚,但检查/比较如果有错误,请使用 php 文档。你是对的,对不起,它是一个 3.x 插件 - 但它只是一个没有依赖关系的特性,如果你选择你可以像使用任何其他 php 供应商代码一样使用它。
    猜你喜欢
    • 2023-02-02
    • 2021-11-16
    • 1970-01-01
    • 2020-09-06
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    相关资源
    最近更新 更多