php - 在 Controller 中使用爬虫

标签 php unit-testing testing symfony

// 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());
    }
}

这在我的测试中工作正常,但我也想在 Controller 中使用这个爬虫。我该怎么做?

我制定路线,并添加到 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');
  }

}

但这会返回错误:

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

最佳答案

WebTestCase 类是一个特殊类,设计用于在测试框架 (PHPUnit) 中运行,您不能在 Controller 中使用它。

但是你可以像这样创建一个 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是类引用

关于php - 在 Controller 中使用爬虫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12282806/

相关文章:

php - 在 DUPLICATE KEY 错误后获取主键?

php - 具有数据库事务的 Laravel Controller-Model 异常处理结构

php - 将 Neo4j DB 与 Laravel 5 集成

swift - 以快速的方式在快速单元测试中模拟静态类方法?

ruby-on-rails - 如何在 shoulda 宏中创建上下文

PHP 简单 html DOM 从 html 标签中删除所有属性

java - TestNG-将参数传递给构造函数,其中参数根据测试名称决定

java - 将 JUnit 测试列表中的所有错误/失败记录到文本文件中

testing - 从测试中向 Nancy 模块发送参数

testing - 如何使用 Webpack jsHint 两个不同的文件夹?