mardi 9 février 2021

PHPUnit tests routing

I'm trying to test a small working router system with phpunit, but I don't know how, for example here my get method. And I would like to know if my code respects the solid principle.

My system is separated into two classes: Router and Route, I do not post the route class because I think I can test it. Thank you!

RouterTest:

<?php

namespace Tests\Http;

use PHPUnit\Framework\TestCase;
use App\Http\Request;
use App\Routing\Router;

class RouterTest extends TestCase 
{
    
    protected $routes;

    protected function setUp(): void
    {  
        $this->request = '/index';
        $this->routes = new Router($this->request);
    }

  public function  testMethodGet()
  {
    $route =  $this->routes->get('/index', 'HomeController@index');
        // $this->assertNotEmpty($this->routes['GET']);
        $this->assertEquals($this->routes, $route); 
        // assertArrayHasKey assertContains assertCount assertEquals assertInstanceOf
  }
}

Router:

<?php

namespace App\Routing;

use App\Http\Request;

/**
 * Router contains the routes and returns the correct route. enter code here
 */
class Router
{
 
    private $request;
    
    private $routes = [];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }
  
    public function get(string $path, string $action)
    {
        return $this->addRoute($path, $action, 'GET');
    }

    /**
     * In the list of routes, we index a route in an array by this method.  
     */
    private function addRoute(string $path, string $action, string $method)
    {
        $route = new Route($path, $action);
        $this->routes[$method][] = $route;
        return $route;
    }

    /**
     * Browse and check if a route matches the URI using the function matches().
     */
    public function run()
    {
        if(!isset($this->routes[$this->request->getMETHOD()])) {
            throw new RouterException('REQUEST_METHOD does not exist');
        }
        foreach ($this->routes[$this->request->getMETHOD()] as $route) {
            if ($route->match($this->request->getUri())) {
                return $route->call();
            }
        }
        throw new RouterException("La page demandée est introuvable.");
    }
}

Aucun commentaire:

Enregistrer un commentaire