schmittjoh / JMSI18nRoutingBundle

Allows you to internationalize your routing
http://jmsyst.com/bundles/JMSI18nRoutingBundle
358 stars 159 forks source link

How to use WebTestCase with JMSi18nRoutingBundle #188

Closed Rebolon closed 8 years ago

Rebolon commented 8 years ago

I'm using JMSI18RoutingBundle on my project with this kind of config : jms_i18n_routing: default_locale: "%locale%" locales: "%locales%" strategy: custom redirect_to_host: true hosts: en: "%urls_en%" de: "%urls_de%"

Everything is ok on prod, dev and test environment. But when i try to run phpunit with a simple webtestcase, the test fail coz this bundle cannot resolve the locale : here is where the code crash JMS/I18nRoutingBundle/Router/I18nRouter.php line 222, methods matchI18n foreach ($availableHosts as $host) { if ($this->hostMap[$currentLocale] === $host) { $differentHost = false; break; } } the $currentLocale is null so it crash. on line 188 $request = $this->getRequest(); is also null

Here is my test :
` namespace Tests\EuronewsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeControllerTest extends WebTestCase { /* * Simple test to check we have a 200 OK + non empty body / public function testShowHome() { $client = static::createClient(); $client->followRedirects(true);

    $url = static::$kernel->getContainer()->getParameter("urls_en");
    $crawler = $client->request('GET', "http://" . $url, ['_locale' => "en", ]);

    $this->assertEquals(200, $client->getResponse()->getStatusCode());
    $this->assertEquals(1,$crawler->filter('body')->count());
    $this->assertNotEquals("", trim($crawler->filter('body')->text()));
}

} `

Because i'm running phpunit, php uses the CLI ISAPI, so i added this method in the AppKernel : ` /* * to enable Request with cli / protected function initializeContainer() { parent::initializeContainer(); if (PHP_SAPI !== 'cli') return;

    $request = new \Symfony\Component\HttpFoundation\Request();
    $requestStack = new \Symfony\Component\HttpFoundation\RequestStack();
    $requestStack->push($request);

    $this->getContainer()->enterScope('request');
    $this->getContainer()->set('request', $request, 'request');
    $this->getContainer()->set('request_stack', $requestStack, 'request');
}/* */

` But in fact it doesn't seem to help the bundle coz the request_stack in the container of the bundle is empty.

Rebolon commented 8 years ago

i got 5minutes to check it again, and it seems to be a mis-configuration in the project.