Use scanner in controller

// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php namespace Acme\DemoBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DemoControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/demo/hello/Fabien'); $this->assertGreaterThan(0, $crawler->filter('html:contains("Hello Fabien")')->count()); } } 

this works fine in my tests, but I would like to use this crawler also in the controller. How can i do this?

I make a route and add to the controller:

 <?php // src/Ens/JobeetBundle/Controller/CategoryController namespace Acme\DemoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Acme\DemoBundle\Entity\Category; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class CategoryController extends Controller { public function testAction() { $client = WebTestCase::createClient(); $crawler = $client->request('GET', '/category/index'); } } 

but this will return me an error:

 Fatal error: Class 'PHPUnit_Framework_TestCase' not found in /acme/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php on line 24 
+6
source share
2 answers

The WebTestCase class is a special class that is designed to run in a test environment (PHPUnit), and you cannot use it in your controller.

But you can create an HTTPKernel client as follows:

 use Symfony\Component\HttpKernel\Client; ... public function testAction() { $client = new Client($this->get('kernel')); $crawler = $client->request('GET', '/category/index'); } 

Please note that you can only use this client to view your Symfony application. If you want to view an external server, you will need to use another client, for example goutte.

The crawler created here is the same crawler that WebTestCase returns, so you can follow the same examples as found in the symfony testing documentation

If you need more information, here is the documentation for the crawler component and here is a class reference

+4
source

You should not use WebTestCase in a prod environment because WebTestCase::createClient() creates a test client.

In your controller, you should do something like this (I recommend you use Buzz\Browser ):

 use Symfony\Component\DomCrawler\Crawler; use Buzz\Browser; ... $browser = new Browser(); $crawler = new Crawler(); $response = $browser->get('/category/index'); $content = $response->getContent(); $crawler->addContent($content); 
+1
source

Source: https://habr.com/ru/post/924636/


All Articles