【问题标题】:Use crawler in controller在控制器中使用爬虫
【发布时间】:2012-08-30 06:05:18
【问题描述】:
// 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

【问题讨论】:

    标签: php unit-testing testing symfony


    【解决方案1】:

    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 testing documentation 中详述的相同示例

    如果您需要更多信息,here 是爬虫组件的文档,here 是类参考

    【讨论】:

    • 谢谢,但是这方面的文档在哪里?我怎样才能获得例如 DIV 或跨类?
    【解决方案2】:

    您不应该在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);
    

    【讨论】:

    • 谢谢,+1。这个浏览器的文档在哪里?如何获取 DOM html 等?
    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多