Is there any way to test a route using PHP Unit in Laravel?

Asked

Viewed 1,510 times

8

I love to create using the PHPunit to create unit tests for my libraries.

Always, before doing the git commit, run it to see if any changes affected what was previously working.

I wish I could also test route by route on Laravel,in a similar way to PHPUnit, so that when I make any changes, I can already have automated tests, instead of going out testing route by route, by browser.

How could I do that in Laravel?

  • 2

    If I understand correctly, the "route test" you refer to, it’s called functional test, or acceptance test (I’m not really sure) you can search the definition of these two... There are other tools that are suitable for this type of test. I recommend this one, which is based on Phpunit: http://codeception.com/

  • @user5978 you’re the man! I’ll take a look at home at that, bro!

1 answer

9


In Laravel specifically you can use the namespace/package classes Illuminate\Foundation\Testing\ (source: https://laravel.com/docs/5.2/testing)

Note that the example here is for Laravel5.2

Inside the folder tests which is inside your Laravel application should contain two files, the TestCase.php which is the "basis" for creating your tests and the ExampleTest.php that you can use to create your tests or else you can create a new file, all files you create should end with Test.php, for example:

  • FooTest.php
  • BarTest.php
  • BazTest.php

An example:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('Laravel 5')
             ->dontSee('Teste');
    }
}
  • The method visit makes a GET request in the application.
  • The method see states that we should see in the application response the text Laravel 5
  • The method dontSee says that we should not see the response text Teste in response to the application

To get all routes you can use the method ->getRoutes(); class \Illuminate\Routing\Router that will return an object of the type: \Illuminate\Routing\RouteCollection and then you can use the getRoutesByMethod (or getRoutes) which is a class method RouteCollection and with that you can create your test.

Your test should look something like:

$routeCollection = Route::getRoutes();

foreach ($routeCollection as $value) {
    $this->visit($value->getPath());
}

It’s just a suggestion, please be sure to criticize if you found any fault, I haven’t used it yet, just followed the documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.