gpt4 book ai didi

PHPUnit - 在测试中自动加载类

转载 作者:IT王子 更新时间:2023-10-29 00:07:00 26 4
gpt4 key购买 nike

我的项目中有以下结构:

/
/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 :在/var/www/phpdev/tests/app/models/UserTableTest 中找不到类 'app\models\UserTable'。第 13 行的 php

我做错了什么?我试图更好地理解 PHPUnit 配置,所以我选择自己编写配置和 Bootstrap 文件。

最佳答案

如果你正在使用 composer autoload

改变

<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();

关于PHPUnit - 在测试中自动加载类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25219764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com