We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Router unit testing

Hi guys,

I am trying to write a unit test for testing my route.

Here is my router.php

use Phalcon\Mvc\Router;

$router = new Router();
$router->setDefaultModule("default");

$router->addGet(
    '/:module/([a-zA-Z0-9_-]+).([a-zA-Z_]+)',
    array(
        'module' => 1,
        'controller' => 2,
        'format' => 3,
        'action' => "index",
    )
);


7.0k

Here is my RouterTest.php It is extends from 'UnitTestCase' phalcon provided.

class RouterTest extends UnitTestCase { protected function setUp() { parent::setUp();

    $config = $this->config;

    $this->di->set(
        'router',
        function() use ($config) {

            require_once __DIR__.'/../../app/core/router.php';
            return $router;
        }
    );

    $this->di->set(
        'request',
        function(){
            return new Request();
        }
    );
}

/**
 * @dataProvider providerTestRouter
 */
public function testRouter($method, $uri, $module, $controller, $action, $params)
{
    $router = $this->di->get('router');
    $router->handle($uri);

    $_SERVER['REQUEST_METHOD'] = $method;

    $this->assertEquals($router->getModuleName(), $module);
    $this->assertEquals($router->getControllerName(), $controller);
    $this->assertEquals($router->getActionName(), $action);
    $this->assertEquals($router->getparams(), $params);
}


7.0k

The route works in real app. just fail to match in the unit test. The data I used for test: $uri = '/mymodule/mycontroller.json'; $method = 'GET';

I am not sure why It is not match the route I defined. it always go to the default module.

Any help would be appreciated.

Thanks in advance



7.0k
Accepted
answer

Solved

Move the line

$_SERVER['REQUEST_METHOD'] = $method

above.