// 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());
}
}
这在我的测试中工作正常,但我也想在控制器中使用此爬虫。我该怎么做?
我制作路由,并添加到控制器:
<?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');
}
}
但这会返回我错误:
Fatal error: Class 'PHPUnit_Framework_TestCase' not found in /acme/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php on line 24
WebTestCase 类是一个特殊的类,设计为在测试框架 (PHPUnit( 中运行,您不能在控制器中使用它。
但是你可以像这样创建一个HTTPKernel客户端:
use Symfony'Component'HttpKernel'Client;
...
public function testAction()
{
$client = new Client($this->get('kernel'));
$crawler = $client->request('GET', '/category/index');
}
请注意,您只能使用此客户端来浏览自己的symfony应用程序。如果要浏览外部服务器,则需要使用另一个客户端,如goutte。
这里创建的爬虫与WebTestCase返回的爬虫相同,因此您可以按照symfony测试文档中详述的相同示例进行操作
如果您需要更多信息,这里是爬网程序组件的文档,这里是类参考
不应prod
环境中使用 WebTestCase
,因为WebTestCase::createClient()
会创建测试客户端。
在你的控制器中,你应该做这样的事情(我建议你使用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);