1

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

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 时,我收到以下错误消息:

塞巴斯蒂安伯格曼的 PHPUnit 3.7.21。

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

onDispatch 调用。乙

时间: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);

}

这一次,我收到以下错误:

塞巴斯蒂安伯格曼的 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 …</p>

有人可以帮我吗?

我们正在使用 Zend Framework 2.2.0。

太感谢了。

欧共体

4

1 回答 1

3

Your mock isn't quite setup right. You don't set any methods for the mock to have and so your expects isn't really being set. You need to create your mock like this:

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

Your User\Model\UserData class doesn't exist and so PHPUnit did not create the method to get mocked. And when you ran your tests the function was not defined.

于 2013-08-14T17:53:51.157 回答