gmarche/tests/Framework/RouterTest.php

60 lines
2.2 KiB
PHP

<?php
namespace Tests\Framework;
use Framework\Router;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\ServerRequest;
use PHPUnit\Framework\TestCase;
class RouterTest extends TestCase {
/**
* @var Router
*/
private $router;
public function setUp()
{
$this->router = new Router();
}
public function testGetMethod()
{
$request = new ServerRequest('GET', '/gmarche');
$this->router->get('/gmarche', function () { return 'hello'; }, 'gmarche');
$route = $this->router->match($request);
$this->assertEquals('gmarche', $route->getName());
$this->assertEquals('hello', call_user_func_array($route->getCallback(), [$request]));
}
public function testGetMethodIfURLDoesNotExists()
{
$request = new ServerRequest('GET', '/gmarche');
$this->router->get('/gmarcheaze', function () { return 'hello'; }, 'gmarche');
$route = $this->router->match($request);
$this->assertEquals(null, $route);
}
public function testGetMethodWithParameters()
{
$request = new ServerRequest('GET', '/gmarche/ile-de-france/paris');
$this->router->get('/gmarche', function () { return 'azezea'; }, 'regions');
$this->router->get('/gmarche/{slug:[a-z0-9\-]+}-{id:\d+}', function () { return 'hello'; }, 'region.show');
$route = $this->router->match($request);
$this->assertEquals('region.show', $route->getName());
$this->assertEquals('hello', call_user_func_array($route->getCallback(), [$request]));
$this->assertEquals(['slug' => 'mon-slug', 'id' => '8'], $route->getParams());
// Test invalid url
$route = $this->router->match(new ServerRequest('GET', '/gmarche/mon_slug-8'));
$this->assertEquals(null, $route);
}
public function testGenerateUri()
{
$this->router->get('/gmarche', function () { return 'azezea'; }, 'regions');
$this->router->get('/gmarche/{slug:[a-z0-9\-]+}-{id:\d+}', function () { return 'hello'; }, 'region.show');
$uri = $this->router->generateUri('region.show', ['slug' => 'region', 'id' => 8]);
$this->assertEquals('/gmarche/region-8', $uri);
}
}