2012-09-05 26 views
6
// 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 

回答

4

的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是類參考

+0

謝謝,但這裏的文檔在哪裏?我怎樣才能得到例如DIV或跨班? –

+1

我更新了我的答案,更多信息 –

+0

非常感謝:) –

1

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); 
+0

謝謝,+1。這個瀏覽器的文檔在哪裏?我如何獲得DOM html等? –