CakePHP “with” method in mock object don't Work

强颜欢笑 提交于 2019-12-24 00:42:27

问题


I'm trying testing my application using CakePHP 2.2 RC1, in the certain action of my controller i need one information of Auth object, in my test i have created an mock object for the Auth component, but when i call the method with my mock object become invalid, when i don't put this everything works fine.

Below the mock object wich dont work

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

Thanks for your attention guys.

--

Edit

Above the full code of my test case, this a very simple test.

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

And the code of my action in the Tag controller, this don't have nothing more (for testing purposes) them a return of user object with count_id as parameter.

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

Running the test I received this message:

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'.


回答1:


After looking at the AuthComponent code, I think the problem lies in the fact that you're not mocking the entire component or you're not mocking the _getUser() method. Don't forget: the methods you're not mocking are real methods!

If you look at the code you'll see that user() is called by _getUser() which in turn is called by startup().

There are two ways to solve this problem, the first is to mock the entire AuthComponent:

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

or mock _getUser() in addition to user():

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

Hopefully, this should solve your problem.




回答2:


I was facing the same issue which I could not solve by the solution provided.

The solution is to use staticExpects() instead of expects() as user is a static function.

$batches->Auth->staticExpects($this->once())->method('user') 
        ->with('id')
        ->will($this->returnValue(1)); 


来源:https://stackoverflow.com/questions/11111383/cakephp-with-method-in-mock-object-dont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!