我的项目中有以下结构:
/
/app
/app/models/ --UserTable.php
/lib
/lib/framework
/lib/framework/Models
/lib/framework/Db
/tests -- phpunit.xml, bootstrap.php
/tests/app
/tests/app/models --UserTableTest.php
有了app和lib目录,我有各种各样的类一起工作来运行我的应用程序。为了设置我的测试,我创建了一个/tests/phpunit.xml文件和一个/tests/bootstrap.php
phpunit.xml
<phpunit bootstrap="bootstrap.php">
</phpunit>
bootstrap.php
<?php
function class_auto_loader($className)
{
$parts = explode('''', $className);
$path = '/var/www/phpdev/' . implode('/', $parts) . '.php';
require_once $path;
}
spl_autoload_register('class_auto_loader');
所以我有下面的测试:
<?php
class UserTableTest extends PHPUnit_Framework_TestCase
{
protected $_userTable;
public function setup()
{
$this->_userTable = new app'models'UserTable;
}
public function testFindRowByPrimaryKey()
{
$user = $this->_userTable->find(1);
$this->assertEquals($user->id, 1);
}
}
但是当我运行测试时,它找不到类- PHP Fatal error: Class 'app'models'UserTable' not found in /var/www/phpdev/tests/app/models/UserTableTest.php on line 13
我做错了什么?我试图更好地理解PHPUnit配置,所以我选择自己编写配置和引导文件。
如果您正在使用composer自动加载
改变 <phpunit colors="true" strict="true" bootstrap="vendor/autoload.php">
<phpunit colors="true" strict="true" bootstrap="tests/autoload.php">
并在tests
目录下创建新的autoload.php
,内容如下
include_once __DIR__.'/../vendor/autoload.php';
$classLoader = new 'Composer'Autoload'ClassLoader();
$classLoader->addPsr4("Your''Test''Namespace''Here''", __DIR__, true);
$classLoader->register();
您可能应该使用编写器来组织代码,例如,编写器。项目根目录下的Json应该包含如下内容:
...
"autoload": {
"psr-0": {
"PRJ_NAME''APP''": "app/",
"PRJ_NAME''LIB''": "lib/"
}
},
...
然后在运行composer update之后,上面定义的两个名称空间被放入vendor/composer/autoload_namespaces.php中。接下来很简单,只需运行带有自动加载选项的phpunit,像这样:
phpunit --bootstrap vendor/autoload.php tests/app/models/UserTableTest
确保在源代码和测试代码中更改名称空间的用法。
如果你在app中使用相同的bootstrap加载classess,你应该能够在测试中加载它们。如果您通过cd运行测试到您的测试目录,只需添加到您的phpunit.xml:
<testsuite name="My Application Tests">
<directory>./</directory>
</testsuite>
<phpunit></phpunit>
内部
在我的加载器(非常接近你的)我检查如果类名的第一个爆炸部分是我的供应商,如果它不是加载器只是返回什么都不做(其他有问题的phpunit的加载器,因为我是新手的phpunit,不知道这是否是预期的行为,也不知道如果phpunit建议或提供加载器准备使用)。
我把phpunit.xml
放在tests/
的同一个目录中(不在里面),一旦配置了<directory>tests</directory>
,我就在命令行上运行phpunit
,没有配置或目录选项。