Mirko Pagliai
Mirko Pagliai

Reputation: 1241

CakePHP 3: tests for controller

I'm writing tests for a controller in a plugin (Assets plugin).

This is the controller:

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;
    }
}

As you can see, it only sends an asset files.

This is the route:

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'],
        ]
    );
});

And this is the test class:

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

Running the test, however, this exception is generated (full test 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

I do not think is a problem of broken, because the same exception is generated by doing so:

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

$this->get($url);

Where am I doing wrong? Thanks.

Upvotes: 1

Views: 715

Answers (1)

Mirko Pagliai
Mirko Pagliai

Reputation: 1241

Solved! On my tests' bootstrap, I missed:

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

Now it works.

Upvotes: 3

Related Questions