PHPUnit - 尝试从作为参数传入的对象中调用方法

时间:2016-04-20 17:56:37

标签: phpunit

我正在尝试测试一个请求对象的方法,该方法作为参数传递给我的函数,但我不断收到错误。知道我可能做错了吗?这就是我所拥有的:

在我的行动助手

public function direct($request)
{
    $myData = $request->getPost('myData');
}

在我的测试文件中

public function testDirect()
{
    $subject = $this->getMockBuilder('Default_Controller_Action_Helper_MyFile')
        ->disableOriginalConstructor()
        ->setMethods(
            array(
                'direct'
            )
        )
        ->getMock();

    $myData = 'myData';

    $request = $this->getMockBuilder('Zend_Controller_Request_Http')
        ->disableOriginalConstructor()
        ->setMethods(array('getPost'))
        ->getMock();

    $request->expects($this->exactly(1))
        ->method('getPost')
        ->with('myData')
        ->will($this->returnValue($myData));

    $subject->direct($request);
}

我收到以下错误:

There was 1 failure:

1) Default_Controller_Action_Helper_MyFile::testDirect
Expectation failed for method name is equal to <string:getPost> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

1 个答案:

答案 0 :(得分:1)

您应该在null定义中将setMethods()传递给$subject,以防止模仿您班级中的方法。

仅删除setMethods调用是不够的,因为默认情况下模拟构建器会模拟所有方法。

这应该有效:

public function testDirect()
{
    $subject = $this->getMockBuilder('Default_Controller_Action_Helper_MyFile')
        ->disableOriginalConstructor()
        ->setMethods(null)
        ->getMock();

    $myData = 'myData';

    $request = $this->getMockBuilder('Zend_Controller_Request_Http')
        ->disableOriginalConstructor()
        ->setMethods(array('getPost'))
        ->getMock();

    $request->expects($this->exactly(1))
        ->method('getPost')
        ->with('myData')
        ->will($this->returnValue($myData));

    $subject->direct($request);
}