Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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",
    )
);


4.3k

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


4.3k

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



4.3k
Accepted
answer

Solved

Move the line

$SERVER['REQUESTMETHOD'] = $method

above.