2017-09-17 115 views
0

我正在爲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文件,僅用於測試。有沒有解決這個問題的方法?

回答

1

路由器需要在應用程序級別上存在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]); 
+0

很抱歉這麼晚纔回復,並且感謝大家的詳細的解答!我已經設置了'CONFIG'常量,但是使用了項目根目錄而不是'tests'目錄。示例配置也非常有用。 – Gus