douzi9744 2015-05-11 11:56
浏览 31

用phpunit抽象控制器中的模拟方法

I want to mock a method with PHPunit in Zend Framework 2.

The method is part of a 'AbstractController' class which is extended by the class I am testing.

The code I use to test:

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

The code in the abstract Controller:

protected function getUserId()
{
    return $this->zfcUserAuthentication()
                    ->getIdentity()
                    ->getId();
}

The code in the controller being tested that requires this method, look at the 2nd parameter in the method being called on the second line of the if statement ($this->getUserId()).

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

I would need the mock the result of this method, but am unable to do so with the current code. The message I receive is as follows: Call to a member function getId() on a non-object in .....

Thank you in advance :)


So I have realised that mocking the abstract was a bad approach and should rather mock the leave request service called by the dispatch method. I have now tried to mock the leave request addLeaveRequestService, but the second parameter $this->getUserId is still being triggered causing the unit test to go the the getId method in the abstract controller where it fails and provides the error message " "call to member function on a non-object"

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 测距传感器数据手册i2c
    • ¥15 RPA正常跑,cmd输入cookies跑不出来
    • ¥15 求帮我调试一下freefem代码
    • ¥15 matlab代码解决,怎么运行
    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法