【发布时间】:2010-09-09 02:29:51
【问题描述】:
我想知道如何使用 Zend_Test 和一般的 PHP 编写 PHPUnit 测试。
【问题讨论】:
标签: php unit-testing zend-framework testing phpunit
我想知道如何使用 Zend_Test 和一般的 PHP 编写 PHPUnit 测试。
【问题讨论】:
标签: php unit-testing zend-framework testing phpunit
我正在使用 Zend_Test 来完全测试所有控制器。设置起来非常简单,因为您只需要设置引导文件(引导文件本身不应该调度前端控制器!)。我的基本测试用例类如下所示:
abstract class Controller_TestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
protected function setUp()
{
$this->bootstrap=array($this, 'appBootstrap');
Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_NonPersistent());
parent::setUp();
}
protected function tearDown()
{
Zend_Auth::getInstance()->clearIdentity();
}
protected function appBootstrap()
{
Application::setup();
}
}
Application::setup(); 完成所有设置任务,这些任务也设置了实际应用程序。一个简单的测试如下所示:
class Controller_IndexControllerTest extends Controller_TestCase
{
public function testShowist()
{
$this->dispatch('/');
$this->assertController('index');
$this->assertAction('list');
$this->assertQueryContentContains('ul li a', 'Test String');
}
}
就是这样……
【讨论】:
他们在 Zend 开发者专区有一个“Introduction to the Art of Unit Testing”,涵盖 PHPUnit。
【讨论】:
我发现this 文章非常有用。 Zend_Test 文档也有很大帮助。 在这两个资源的帮助下,我成功地在 Zend Framework 的QuickStart tutorial 中实现了单元测试,并为其编写了一些测试。
【讨论】:
使用 ZF 1.10,我将一些引导代码放入 tests/bootstrap.php(基本上是 (public/index.php) 中的内容,直到 $application->bootstrap()。
然后我可以使用
运行测试phpunit --bootstrap ../bootstrap.php PersonControllerTest.php
【讨论】:
我没有使用 Zend_Test,但我已经使用 Zend_MVC 等针对应用程序编写了测试。最重要的部分是在测试设置中获得足够的引导代码。
【讨论】:
另外,如果您使用数据库事务,那么最好删除所有通过单元测试完成的事务,否则您的数据库会变得一团糟。
等设置
public function setUp() {
YOUR_ZEND_DB_INSTANCE::getInstance()->setUnitTestMode(true);
YOUR_ZEND_DB_INSTANCE::getInstance()->query("BEGIN");
YOUR_ZEND_DB_INSTANCE::getInstance()->getCache()->clear();
// Manually Start a Doctrine Transaction so we can roll it back
Doctrine_Manager::connection()->beginTransaction();
}
在拆卸时,您需要做的就是回滚
public function tearDown() {
// Rollback Doctrine Transactions
while (Doctrine_Manager::connection()->getTransactionLevel() > 0) {
Doctrine_Manager::connection()->rollback();
}
Doctrine_Manager::connection()->clear();
YOUR_ZEND_DB_INSTANCE::getInstance()->query("ROLLBACK");
while (YOUR_ZEND_DB_INSTANCE::getInstance()->getTransactionDepth() > 0) {
YOUR_ZEND_DB_INSTANCE::getInstance()->rollback();
}
YOUR_ZEND_DB_INSTANCE::getInstance()->setUnitTestMode(false);
}
【讨论】: