PHPUnit的returnValueMap没有产生预期的结果

PHPUnit的returnValueMap没有产生预期的结果

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

问题描述

我正在尝试使用PHPUnit的可对读取结果进行存根。它没有产生预期的结果,但是等效的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 Framework中的示例函数:

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))));

如果中间没有空值,它将不起作用。

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

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

08-05 15:02