单元测试CakePHP 3插件需要一个config/routes.php文件夹来测试Router :: url()
我正在为CakePHP 3插件编写一些测试,并且我的一些操作使用Router::url
调用。当我运行phpunit时出现以下错误:include([project dir]\\config\routes.php): failed to open stream: No such file or directory
。单元测试CakePHP 3插件需要一个config/routes.php文件夹来测试Router :: url()
我想知道的是,如果这个文件真的只需要单元测试工作。如果我在该文件夹上创建文件,则测试正常。我曾尝试加入
DispatcherFactory::add('Asset'); DispatcherFactory::add('Routing'); DispatcherFactory::add('ControllerFactory');
我tests/bootstrap.php
文件,但它并没有任何改变。
由于这是一个独立的插件,我发现有一个config
文件夹,其中包含一个routes.php
文件,仅用于测试。有没有解决这个问题的方法?
路由器需要在应用程序级别上存在routes.php
文件,因此您应该做的是配置可放置此类文件的测试应用程序环境。
在您的tests/bootstrap.php
文件中,定义测试环境所需的常量和配置。如果它只是其中用于路由器,它很可能是不够的,如果你定义CONFIG
不变。因此,这是在\Cake\Routing\Router::_loadRoutes()
被使用,像
define('CONFIG', dirname(__DIR__) . DS . 'tests' . DS . 'TestApp' . DS . 'config' . DS);
这将在配置目录设置为tests/TestApp/config/
,在那里你可以放置routes.php
文件。
一般来说,我会建议设置所有的常量,并至少基本的应用程序的配置,这里是从我的插件之一的例子:
use Cake\Core\Configure;
use Cake\Core\Plugin;
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
define('ROOT', dirname(__DIR__));
define('APP_DIR', 'src');
define('APP_ROOT', ROOT . DS . 'tests' . DS . 'TestApp' . DS);
define('APP', APP_ROOT . APP_DIR . DS);
define('CONFIG', APP_ROOT . DS . 'config' . DS);
define('WWW_ROOT', APP . DS . 'webroot' . DS);
define('TESTS', ROOT . DS . 'tests' . DS);
define('TMP', APP_ROOT . DS . 'tmp' . DS);
define('LOGS', APP_ROOT . DS . 'logs' . DS);
define('CACHE', TMP . 'cache' . DS);
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp');
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
define('CAKE', CORE_PATH . 'src' . DS);
require_once ROOT . DS . 'vendor' . DS . 'autoload.php';
require_once CORE_PATH . 'config' . DS . 'bootstrap.php';
$config = [
'debug' => true,
'App' => [
'namespace' => 'App',
'encoding' => 'UTF-8',
'defaultLocale' => 'en_US',
'base' => false,
'baseUrl' => false,
'dir' => 'src',
'webroot' => 'webroot',
'wwwRoot' => WWW_ROOT,
'fullBaseUrl' => 'http://localhost',
'imageBaseUrl' => 'img/',
'cssBaseUrl' => 'css/',
'jsBaseUrl' => 'js/',
'paths' => [
'plugins' => [APP_ROOT . 'plugins' . DS],
'templates' => [APP . 'Template' . DS],
'locales' => [APP . 'Locale' . DS],
],
]
];
Configure::write($config);
date_default_timezone_set('UTC');
mb_internal_encoding(Configure::read('App.encoding'));
ini_set('intl.default_locale', Configure::read('App.defaultLocale'));
Plugin::load('MyPlugin', ['path' => ROOT]);
很抱歉这么晚才回复,并且感谢大家的详细的解答!我已经设置了'CONFIG'常量,但是使用了项目根目录而不是'tests'目录。示例配置也非常有用。 – Gus