2012-07-03 19 views
2

我有一個適用於我的symfony應用程序的phpunit測試套件。在那個測試文件中,我在不同的測試之間有一些依賴關係,並且在依賴關係之間傳遞一個DOMCrawler對象,這樣我就不必每次都找到它。爲什麼symfony DOMCrawler對象在相關的phpunit測試之間沒有正確傳遞?

但是,在採取我所做的方法時,您似乎無法使用這些傳遞的對象提交表單,但可以單擊它們上的鏈接。是否有一個原因?我的設計很差,如果是這樣,我應該如何改變它?歡迎任何反饋。我附上了一些代碼。

<?php 

namespace someBundle\Tests\Controller; 

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; 

/** 
* blah Controller Test 
* 
*/ 
class BlahControllerTest extends WebTestCase 
{ 

    private $adminUrl; 

    /** 
    * Constructs basic information for a audit report controller test suite 
    * 
    */ 
    public function __construct() 
    { 
     $this->adminUrl = '/admin/'; 
    } 

    /** 
    * Starts a test suite 
    * 
    * @return Crawler 
    */ 
    public function testAdd() 
    { 
     // Create a new client to browse the application 
     $client = static::createClient(); 

     // Go to site specific admin url 
     $crawler = $client->request('GET', $this->adminUrl); 
     $this->assertTrue(200 === $client->getResponse()->getStatusCode()); 

     // do stuff here 

     // goes to edit page 
     $crawler = $client->request('GET', $editPage); 

     return $crawler; 
    } 

    /** 
    * Tests the edit functionality 
    * 
    * @param Crawler $crawler Crawler for the show view 
    * 
    * @depends testAdd 
    */ 
    public function testEdit($crawler) 
    { 
     // Create a new client to browse the application 
     $client = static::createClient(); 

     //Line below is included if the crawler points to the show view 
     //$crawler = $client->click($crawler->selectLink('Edit')->link()); 

     // Fill in the form and submit it 
     $form = $crawler->selectButton('Edit')->form(array(
      $foo => $bar, 
     )); 

     // The following line doesn't work properly if testEdit is passed the 
     // edit page. However, if it is passed the show page, and the 
     // edit link above is clicked, then the form will submit fine. 
     $client->submit($form); 
     $crawler = $client->followRedirect(); 

     // more code here... 
    } 
} 
+0

依賴測試是應該避免的。如果你的測試有一個共同的部分,你應該使它成爲setUp的一部分,或者有一個輔助方法爲你做。您應該始終能夠單獨運行一個測試並獲得預期的結果。 –

回答

3

的原因是,因爲你可以在WebTestCase類來擴展它看到的,拆機實現:

protected function tearDown() 
{ 
    if (null !== static::$kernel) { 
     static::$kernel->shutdown(); 
    } 
} 

內核的這種關機有很多的影響。一種效應就是你正在經歷的。我試圖追查一次究竟發生了什麼,但是我沒有得到任何地方,只是記住了一旦關閉被調用,客戶端和爬蟲就沒用了。

我會推薦與Louis相同的東西:讓你的測試獨立。除此之外,它不與客戶合作,請考慮在創建頁面上發生什麼事的時間。實際上,您的編輯頁面測試也會中斷,儘管頁面本身可能沒問題。

取決於通常用於進一步驗證對象,如果您想要更深入地測試響應。您將使用依賴測試並返回第一個響應。在這種情況下,兩個測試都可以中斷,因爲如果您的創建頁面中斷,當然您的響應內容看起來不像應該。

相關問題