【问题标题】:Trouble running unit test - got undefined method error运行单元测试时遇到问题 - 出现未定义的方法错误
【发布时间】:2013-08-02 13:35:00
【问题描述】:

我按照此页面上的说明进行操作,但无法进行单元测试。

http://framework.zend.com/manual/2.2/en/tutorials/unittesting.html

我的初始代码是这样的:

<?php

namespace ApplicationTest\Controller;

use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

class IndexControllerTest extends AbstractHttpControllerTestCase {

    protected $controller;
    protected $request;
    protected $response;
    protected $routeMatch;
    protected $event;
    protected $traceError = true;

    public function setUp() {

        $this->setApplicationConfig(
            include '../../../config/application.config.php'
        );
        parent::setUp();
    }

    public function testIndexActionCanBeAccessed() {

        $this->dispatch('/');
        $this->assertResponseStatusCode(200);

    }
}

当我运行 phpunit 时,我收到以下错误消息:

Sebastian Bergmann 的 PHPUnit 3.7.21。

从 /usr/share/php/tool/module/Application/test/phpunit.xml 读取配置

onDispatch 调用。 E

时间:1 秒,内存:14.50Mb

有 1 个错误:

1) ApplicationTest\Controller\IndexControllerTest::testIndexActionCanBeAccessed Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get 无法获取或创建 Zend\Db\Adapter\Adapter 的实例

然后我按照第二组说明来配置服务管理器。

public function testIndexActionCanBeAccessed() {

    $albumTableMock = $this->getMockBuilder('User\Model\UserData')
        ->disableOriginalConstructor()
        ->getMock();

    $albumTableMock->expects($this->once())
        ->method('getUserSessionArray')
        ->will($this->returnValue(array()));

    $serviceManager = $this->getApplicationServiceLocator();
    $serviceManager->setAllowOverride(true);
    $serviceManager->setService('User\Model\UserData', $albumTableMock);

    $this->dispatch('/');
    $this->assertResponseStatusCode(200);

}

这一次,我得到了以下错误:

Sebastian Bergmann 的 PHPUnit 3.7.21。

从 /usr/share/php/tool/module/Application/test/phpunit.xml 读取配置

onDispatch 调用。 PHP 致命错误:在第 95 行的 /usr/share/php/tool/module/User/Module.php 中调用未定义的方法 Mock_UserData_ae821217::getUserSessionArray() PHP堆栈跟踪: PHP 1. {main}() /usr/local/pear/bin/phpunit:0 …

有人可以帮我解决这个问题吗?

我们正在使用 Zend Framework 2.2.0。

非常感谢。

EC

【问题讨论】:

    标签: phpunit zend-framework2


    【解决方案1】:

    您的模拟设置不正确。您没有为模拟设置任何方法,因此您的期望并没有真正设置。你需要像这样创建你的模拟:

    $albumTableMock = $this->getMockBuilder('User\Model\UserData')
        ->disableOriginalConstructor()
        ->setMethods(array('getUserSessionArray'))  //ADD this line
        ->getMock();
    

    您的 User\Model\UserData 类不存在,因此 PHPUnit 没有创建被模拟的方法。当你运行测试时,函数没有定义。

    【讨论】:

    • 谢谢。然而,ZF2 文档中排除和/或忽略或遗忘了另一段非常重要的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多