Skip to content

Use TestWith() attribute to test routes #21

@tacman

Description

@tacman

I've been playing around with the functional test generator and phpunit 10+ with php 8 (attributes), where we can use with TestWith attribute. The code is much smaller.

namespace App\Tests;

use PHPUnit\Framework\Attributes\TestWith;
use Pierstoval\SmokeTesting\FunctionalSmokeTester;
use Pierstoval\SmokeTesting\FunctionalTestData;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class FunctionalTest extends WebTestCase
{
    use FunctionalSmokeTester;

    #[TestWith(['/api','api_entrypoint'])]
    #[TestWith(['/','app_homepage'])]
    public function testRoute(string $url, string $route, string $method='GET'): void
    {
        $this->runFunctionalTest(
            FunctionalTestData::withUrl($url)
                ->withMethod($method)
                ->expectRouteName($route)
                ->appendCallableExpectation($this->assertStatusCodeLessThan500($method, $url))
        );

    }

    public function assertStatusCodeLessThan500(string $method, string $url): \Closure
    {
        return function (KernelBrowser $browser) use ($method, $url) {
            $statusCode = $browser->getResponse()->getStatusCode();
            $routeName = $browser->getRequest()->attributes->get('_route', 'unknown');

            static::assertLessThan(
                500,
                $statusCode,
                sprintf('Request "%s %s" for %s route returned an internal error.', $method, $url, $routeName),
            );
        };
    }
}

If you like the approach, I can make a PR. The main issue is that it only works with PHP8+ and phpunit 10+.

Would you be open to use nette/php-generator to create the test? It always generates valid PHP code, and will adjust to the version of PHP being used. It adds a dependency, but it gets rid of the php template that generates PHP.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions