Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于phpunit的抽象控制器模拟方法_Php_Unit Testing_Zend Framework2_Phpunit - Fatal编程技术网

基于phpunit的抽象控制器模拟方法

基于phpunit的抽象控制器模拟方法,php,unit-testing,zend-framework2,phpunit,Php,Unit Testing,Zend Framework2,Phpunit,我想在Zend Framework 2中用PHPunit模拟一个方法 该方法是“AbstractController”类的一部分,该类由我正在测试的类扩展 我用于测试的代码: public function testAddPostAction() { $this->mockBjy(); $this->mockZFC(); $zfcUser = $this->getMockBuilder('Common\Controller\AbstractContr

我想在Zend Framework 2中用PHPunit模拟一个方法

该方法是“AbstractController”类的一部分,该类由我正在测试的类扩展

我用于测试的代码:

 public function testAddPostAction()
{
    $this->mockBjy();
    $this->mockZFC();

    $zfcUser = $this->getMockBuilder('Common\Controller\AbstractController')->getMock();
    $zfcUser ->method('getUserId')
            ->will($this->returnValue('2'));
      $this->assertEquals(2, $zfcUser->getUserId());

    $this->dispatch('/leaverequest/add','POST', array('user' => '2','reasonforleave' => 'PHPunit','leaveRequestDates'=> '05/06/2015 - 05/15/2015'));
    $this->assertModuleName('Employment');
    $this->assertControllerName('employment\controller\leaverequest');
    $this->assertControllerClass('LeaveRequestController');
    $this->assertActionName('add');
    $this->assertMatchedRouteName('leaverequest/add');
}
抽象控制器中的代码:

protected function getUserId()
{
    return $this->zfcUserAuthentication()
                    ->getIdentity()
                    ->getId();
}
要测试的控制器中需要此方法的代码,请查看if语句第二行调用的方法中的第二个参数($this->getUserId())

我需要模拟这个方法的结果,但是用当前的代码无法这样做。我收到的消息如下:对..中的非对象调用成员函数getId()

提前感谢:)


因此,我意识到模拟抽象是一种糟糕的方法,应该模拟dispatch方法调用的请假请求服务。我现在已经尝试模拟leave request addLeaveRequestService,但是第二个参数$this->getUserId仍然被触发,导致单元测试在抽象控制器中的getId方法失败并提供错误消息“
“对非对象调用成员函数“

您不需要在
调度
调用中使用的服务定位器上设置模拟对象。我也不明白为什么要模拟抽象控制器,而不是
dispatch
最终使用的控制器。你看过报纸了吗?Dispatch最终使用$this->getUserId,$这是指由我正在测试的类扩展的abstractController。根据我的理解,我不能将abstractController视为服务。如果不是,请纠正我。我正在查看文档,但没有找到解决方案。
public function addAction()
{
    if ($this->getRequest()->isPost()) {
        $this->getServiceLocator()->get('leaveRequestService')->addLeaveRequest($this->getRequest()->getPost()->toArray(), $this->getUserId());
        $returnValue = $this->redirect()->toRoute('leaverequest/list');
    } else {
        $users = $this->getServiceLocator()->get('userService')->findAllUsers();
        $returnValue = new ViewModel(array('users' => $users));
    }
    return $returnValue;
}