PHPUnit-测试中的自动加载类 [英] PHPUnit - autoload classes within tests
问题描述
我的项目中具有以下结构:
I have the following structure within my project:
/
/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
With the app and lib directories I have various classes that work together to run my app. To setup my tests I have create a /tests/phpunit.xml file and a /tests/bootstrap.php
phpunit.xml
phpunit.xml
<phpunit bootstrap="bootstrap.php">
</phpunit>
bootstrap.php
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');
因此,我进行了以下测试:
So I have the following test:
<?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
But it can't find the class when I run the test - PHP Fatal error: Class 'app\models\UserTable' not found in /var/www/phpdev/tests/app/models/UserTableTest.php on line 13
我做错了什么?我试图更好地理解PHPUnit配置,所以我选择自己编写配置和引导文件.
What am I doing wrong? I'm trying to understand PHPUnit configuration better so I opted to write the configuration and bootstrap file myself.
推荐答案
如果您正在使用composer自动加载
If you are using composer autoload
更改
<phpunit colors="true" strict="true" bootstrap="vendor/autoload.php">
到
<phpunit colors="true" strict="true" bootstrap="tests/autoload.php">
并在tests
目录中创建具有以下内容的新autoload.php
and in tests
directory create new autoload.php
with following content
include_once __DIR__.'/../vendor/autoload.php';
$classLoader = new \Composer\Autoload\ClassLoader();
$classLoader->addPsr4("Your\\Test\\Namespace\\Here\\", __DIR__, true);
$classLoader->register();
这篇关于PHPUnit-测试中的自动加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!