Justin
Justin

Reputation: 21

PHPUnit WebTestCase using native session when mock session is configured, Symfony 5

I am getting the "Failed to start the session because headers have already been sent" error when running the sample smoke test url example from Symfony, https://symfony.com/doc/5.3/best_practices.html#smoke-test-your-urls

<?php

namespace App\Tests;

use Generator;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ApplicationAvailabilityFunctionalTest extends WebTestCase
{
    /**
     * @dataProvider urlProvider
     */
    public function testPageIsSuccessful($url)
    {
        $client = self::createClient();
        $client->request('GET', $url);

        $this->assertResponseIsSuccessful();
    }

    public function urlProvider(): Generator
    {
        yield ['/'];
    }
}

I have configured mock sessions in my config/packages/framework.yaml file. There are no other overrides in the config/packages/test folder.

when@test:
    framework:
        test: true
        session:
            storage_factory_id: session.storage.factory.mock_file

The phpunit.xml.dist file has the appropriate environment specified for the "test" environment.

<server name="APP_ENV" value="test" force="true" />

It makes no difference whether I execute the test form within PHPStorm or from console via php bin/phpunit. I must be missing something with the configuration. Any ideas?

Here is a stack trace leading to the native session: enter image description here

Upvotes: 1

Views: 965

Answers (1)

Justin
Justin

Reputation: 21

Answered my own question, but @dbrumann had me heading in the right direction with the event listener hint. Thanks

I added to services.yaml, the event listeners only for non-test environments.

when@dev:
    services:
        Symfony\Component\HttpKernel\Profiler\Profiler: '@profiler'
        App\EventListener\RequestListener:
            tags:
                - { name: kernel.event_listener, event: kernel.request }

        App\EventListener\ResponseListener:
            tags:
                - { name: kernel.event_listener, event: kernel.response }

when@prod:
    services:
        App\EventListener\RequestListener:
            tags:
                - { name: kernel.event_listener, event: kernel.request }

        App\EventListener\ResponseListener:
            tags:
                - { name: kernel.event_listener, event: kernel.response }

Upvotes: 1

Related Questions