模拟对象中的 CakePHP "with"方法不起作用

标签 cakephp authentication mocking phpunit

我正在尝试使用 CakePHP 2.2 RC1 测试我的应用程序,在我的 Controller 的特定操作中我需要一个 Auth 对象的信息,在我的测试中我为 Auth 组件创建了一个模拟对象,但是当我调用该方法时 我的模拟对象变得无效,当我不把它一切正常。

在不起作用的模拟对象下面

$this->controller->Auth
    ->staticExpects($this->any())
    ->method('user')
    ->with('count_id')
    ->will($this->returnValue(9));

感谢大家的关注。

--

编辑

上面是我的测试用例的完整代码,这是一个非常简单的测试。

class TagsControllerTest extends ControllerTestCase {
    public function testView(){
        $Tags = $this->generate('Tags', array(
            'components' => array(
                'Session',
                'Auth' => array('user')
            )
        ));
        $Tags->Auth->staticExpects($this->any())
            ->method('user')
            ->with('count_id')
            ->will($this->returnValue(2));

        $result = $this->testAction('/tags/view');
        $this->assertEquals($result, 2);
    }
}

我在 Tag Controller 中的操作代码,仅此而已(出于测试目的),它们返回以 count_id 作为参数的用户对象。

public function view(){
    return $this->Auth->user('count_id');
}

运行测试我收到这条消息:

Expectation failed for method name is equal to when invoked zero or more times Parameter 0 for invocation AuthComponent::user(null) does not match expected value. Failed asserting that null matches expected 'count_id'.

最佳答案

在查看了 AuthComponent 代码之后,我认为问题在于您没有模拟整个组件或者您没有模拟_getUser() 方法。不要忘记:您没有模拟的方法是真实方法!

如果您查看代码,您会发现 user()_getUser() 调用,而 _getUser() 又由 startup()< 调用.

解决这个问题有两种方法,第一种是mock整个AuthComponent:

$Tags = $this->generate('Tags', array(
        'components' => array(
            'Session',
            'Auth' /* no methods */
        )
    ));

或模拟 _getUser() 除了 user():

$Tags = $this->generate('Tags', array(
        'components' => array(
            'Session',
            'Auth' => array('user', '_getUser')
        )
    ));

希望这能解决您的问题。

关于模拟对象中的 CakePHP "with"方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111383/

相关文章:

mysql - 在 CakePHP 中从一个表中检索所有数据,并从另一个表中检索一些数据

php - CakePHP:为什么我无法使用 set() 或 save() 更新记录?

API认证设计

mocking - Mockito.mockedStatic 用于带参数的方法

mysql - 另一个 "need to pull data from two tables in cakephp"

javascript - 如何在 gatsby 中对用户进行身份验证

c# - 针对 Active Directory 验证 NT 和 LM 哈希

java - Getmethod Mokito java 模拟

javascript - 模拟 Angular $resource

cakephp - 在 cakePHP 中使用复选框的隐藏字段