本文介绍了PHPUnit 的 returnValueMap 没有产生预期的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PHPUnit 的 returnValueMap() 将读取的结果存根.它没有产生预期的结果,但等效的 returnCallback() 可以.如果您想亲自检查,我已经提供了我的测试用例.

I'm trying to use PHPUnit's returnValueMap() to stub out the results of a read. It isn't yielding the expected results, but an equivalent returnCallback() does. I've made my test case available if you'd like to inspect it yourself.

returnValueMap()

$enterprise = $this->getMock('Enterprise', array('field'));
$enterprise->expects($this->any())
    ->method('field')
    ->will($this->returnValueMap(array(
        array('subscription_id', null),
        array('name', 'Monday Farms')
    )));
$enterprise->subscribe('basic');

结果:

Subscription ID: NULL
Name: NULL

returnCallback()

$enterprise = $this->getMock('Enterprise', array('field'));
$enterprise->expects($this->any())
    ->method('field')
    ->will($this->returnCallback(function ($arg) {
        $map = array(
            'subscription_id' => null,
            'name' => 'Monday Farms'
        );
        return $map[$arg];
    }));
$enterprise->subscribe('basic');

结果:

Subscription ID: NULL
Name: string(12) "Monday Farms"

企业::订阅

public function subscribe() {
    echo 'Subscription ID: ';
    var_dump($this->field('subscription_id'));
    echo 'Name: ';
    var_dump($this->field('name'));
}

为什么 returnValueMap() 没有像我期望的那样工作?我到底错过了什么?

Why doesn't returnValueMap() work as I expect it to? What exactly am I missing?

推荐答案

我遇到了同样的问题,最后发现 returnValueMap() 必须映射你函数的所有参数,包括可选参数,然后是所需的返回值.

I had the same problem and eventually found out that returnValueMap() has to map all parameters of your function, including optional ones, then the desired return value.

来自 Zend 框架的示例函数:

Example function from Zend Framework:

public function getParam($key, $default = null)
{
    $key = (string) $key;
    if (isset($this->_params[$key])) {
        return $this->_params[$key];
    }

    return $default;
}

必须像这样映射:

$request->expects($this->any())
        ->method('getParam')
        ->will($this->returnValueMap(array(array($param, null, $value))));

中间没有null,就不行了.

Without the null in the middle, it won't work.

这篇关于PHPUnit 的 returnValueMap 没有产生预期的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 16:16