PHPUnit:模拟 __get() 结果为 "__get() must take exactly 1 argument ..."

标签 php phpunit overloading built-in

我在模拟重载的 __get($index) 方法时遇到问题。 被模拟的类和使用它的被测系统的代码如下:

<?php
class ToBeMocked
{
    protected $vars = array();

    public function __get($index)
    {
        if (isset($this->vars[$index])) {
            return $this->vars[$index];
        } else {
            return NULL;
        }
    }
}

class SUTclass
{
    protected $mocky;

    public function __construct(ToBeMocked $mocky)
    {
        $this->mocky = $mocky;
    }

    public function getSnack()
    {
        return $this->mocky->snack;
    }
}

测试如下:

<?php    
class GetSnackTest extends PHPUnit_Framework_TestCase
{
    protected $stub;
    protected $sut;

    public function setUp()
    {
       $mock = $this->getMockBuilder('ToBeMocked')
                     ->setMethods(array('__get')
                     ->getMock();

       $sut = new SUTclass($mock);
    }

    /**
     * @test
     */
    public function shouldReturnSnickers()
    {
        $this->mock->expects($this->once())
                   ->method('__get')
                   ->will($this->returnValue('snickers');

        $this->assertEquals('snickers', $this->sut->getSnack());
    }
}

真实的代码稍微复杂一点,但并不复杂,因为它的父类中有“getSnacks()”。但这个例子应该足够了。

问题是在使用 PHPUnit 执行测试时出现以下错误:

Fatal error: Method Mock_ToBeMocked_12345672f::__get() must take exactly 1 argument in /usr/share/php/PHPUnit/Framework/MockObject/Generator.php(231)

当我调试时,我什至无法到达测试方法。看起来它在设置模拟对象时中断了。

有什么想法吗?

最佳答案

__get() 接受一个参数,因此您需要为模拟提供一个参数:

/**
 * @test
 */
public function shouldReturnSnickers()
{
    $this->mock->expects($this->once())
               ->method('__get')
               ->with($this->equalTo('snack'))
               ->will($this->returnValue('snickers'));

    $this->assertEquals('snickers', $this->sut->getSnack());
}

with() 方法为 PHPUnit 中的模拟方法设置参数。您可以在Test Doubles部分找到更多详细信息。 .

关于PHPUnit:模拟 __get() 结果为 "__get() must take exactly 1 argument ...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110833/

相关文章:

php - 可在多个相册文件夹中查找的动态图像库

php - 用 PHP 编写归并排序

Laravel 使用assertJson 测试集合JSON 响应

java - 重载或者普通方法

c++ - 在 C++ 中重载 IO 运算符时使用 cout/cin?

c++ - 为什么这两个函数不能重载呢?

php - 使用 PHP 和 MySQL 的每行页面

php - Composer 要求 ext-zip 失败

PHPUnit 测试错误 : Object of class (. ..) 无法转换为字符串

php - 模拟框架返回具有不同名称和类型的类