原文:
http://packages.zendframework.com/docs/latest/manual/en/user-guide/unit-testing.html
一个可靠的单元测试在大型项目中对推进项目有着很重要的作用,尤其是很多人参与的时候。在每次做了修改之后回测各个单元。你的单元测试能够帮助你在测试中发现很多问题。
ZF2 API是使用PHPUnit,同样我们这个教程应用也适用。至于阐述单元测试的详细细节已经不在我们这篇教程的讨论范围之内了,所以我们也就写一些简单的测试来进行一些组件的测试。这篇教程也假设你已经安装了PHPUnit测试扩展。
建立测试目录
在项目根目录文件夹中创建一个叫做tests文件夹的子目录:
zf2-tutorial/
/tests
/module
/Application
/src
/Application
/Controller
tests目录一般也在项目文件夹中,同时你可以按照你的意愿来组织并且很容易发现。之后,你可以创建一些目录来测试你的models,但是此刻我们这就列出IndexController来测试Application Module。
启动你的测试
然后,在 zf-tutorial/tests/ 创建一个 phpunit.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="bootstrap.php">
<testsuites>
<testsuite name="zf2tutorial">
<directory>./</directory>
</testsuite>
</testsuites>
</phpunit>
增加一个 bootstrap.php ,当然也是在 zf-tutorial/tests/ 文件夹下面:
chdir(dirname(__DIR__));
include __DIR__ . '/../init_autoloader.php';
这个启动文件的内容和 zf-tutorial/public/index.php 差不多。除了我们不初始化应用外。我们将会开始我们的测试以便每个测试都能够针对每个新建的应用实例,而不会出现之前的测试影响到测试结果。
你的第一个测试
下一步,zf-tutorial/tests/module/Application/src/Application/Controller 创建 IndexControllerTest.php:
<?php
namespace Application\Controller;
use Application\Controller\IndexController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use PHPUnit_Framework_TestCase;
class IndexControllerTest extends PHPUnit_Framework_TestCase
{
protected $controller;
protected $request;
protected $response;
protected $routeMatch;
protected $event;
protected function setUp()
{
$bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php');
$this->controller = new IndexController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = $bootstrap->getMvcEvent();
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setEventManager($bootstrap->getEventManager());
$this->controller->setServiceLocator($bootstrap->getServiceManager());
}
}
这里,我们扩展了一下 Tom Oram’s Unit Testing a ZF 2 Controller ,在控制器里的Setup方法我们初始化应用,并且设置了时间管理及服务定位。此刻这不是很重要的,但是在我们写更高级的测试的时候会用到的。
现在,在 IndexControllerTest 类中添加以下函数:
public function testIndexActionCanBeAccessed()
{
$this->routeMatch->setParam('action', 'index');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
$this->assertInstanceOf('Zend\View\Model\ViewModel', $result);
}
这个测试返回200代码及 Zend\View\Model\ViewModel 实例。
测试
最后,cd(切换文件夹)到 zf-tutorial/tests/ 文件夹下,然后执行 phpunit。如果你可以看到如下输出,那么证明你的应用已经做好了更多测试的准备:
PHPUnit 3.5.15 by Sebastian Bergmann.
.
Time: 0 seconds, Memory: 5.75Mb
OK (1 test, 2 assertions)