CakePHP 3:测试控制器

时间:2016-09-19 12:53:04

标签: cakephp cakephp-3.0

我正在为插件(Assets插件)中的控制器编写测试。

这是控制器:

namespace Assets\Controller;

use Cake\Controller\Controller;

class AssetsController extends Controller
{
    public function asset($filename, $type)
    {
        $this->response->type($type);
        $this->response->file(ASSETS . DS . $filename);

        return $this->response;
    }
}

如您所见,它只发送资产文件。

这是路线:

Router::plugin('Assets', ['path' => '/assets'], function ($routes) {
    $routes->connect(
        '/:type/:filename',
        ['controller' => 'Assets', 'action' => 'asset'],
        [
            'type' => '(css|js)',
            'filename' => '[a-z0-9]+\.(css|js)',
            'pass' => ['filename', 'type'],
        ]
    );
});

这是测试类:

namespace Assets\Test\TestCase\Controller;

use Assets\Utility\AssetsCreator;
use Cake\TestSuite\IntegrationTestCase;

class AssetsControllerTest extends IntegrationTestCase
{    
    public function testAsset()
    {
        //This is the filename
        $filename = sprintf('%s.%s', AssetsCreator::css('test'), 'css');

        $this->get(sprintf('/assets/css/%s', $filename));

        $this->assertResponseOk();
    }
}

然而,运行测试会生成此异常(完整测试here):

1) Assets\Test\TestCase\Controller\AssetsControllerTest::testAsset
Cake\Routing\Exception\MissingControllerException: Controller class  could not be found. in /home/mirko/Libs/Plugins/Assets/vendor/cakephp/cakephp/src/Http/ControllerFactory.php:91

我认为这不是一个破碎的问题,因为这样做会产生同样的异常:

$url = \Cake\Routing\Router::url([
    'controller' => 'Assets',
    'action' => 'asset',
    'plugin' => 'Assets',
    'type' => 'css',
    'filename' => $filename,
]);

$this->get($url);

我在哪里做错了?感谢。

1 个答案:

答案 0 :(得分:2)

解决!在我测试的引导程序中,我错过了:

DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');

现在可行。