2016-11-21 37 views
2

我不明白我的代碼的行爲。下面是一個簡單的版本:phpunit中的特質TestCase

我有一個測試:

class EditVoterTest extends TestCase 
{ 
    use ContainerAwareTrait; 

    protected function setUp() 
    { 
     $this->getContainer(); 
    } 

    public function testSomething() 
    { 
     // test lauched 4 times with a provider 
    } 
} 

和特點:

trait ContainerAwareTrait 
{ 
    private $container; 

    public function getContainer() 
    { 
     if (!$this->container) { 
      echo "NO CONTAINER \n"; 
      $this->container = true; 
     } 

     return $this->container; 
    } 
} 

,其結果是

PHPUnit 5.6.2 by Sebastian Bergmann and contributors. 

.NO CONTAINER 
.NO CONTAINER 
.NO CONTAINER 
.                4/4 (100%)NO CONTAINER 


Time: 241 ms, Memory: 21.00MB 

爲什麼容器「構建「 每一次 ?

+0

我認爲,對於每一個測試,正在創建測試類的新實例。 –

+1

對於每個測試,PHPUnit將運行'setUp()' –

+0

正如@FelippeDuarte所說,'setUp'是設計用於在執行任何測試(實例化對象,連接資源等)之前完成所有必要事情的方法。所以,作爲單元測試的手段,每個測試都必須被認爲是唯一的,因此每個測試都必須執行'setUp'。 –

回答

0

根據文檔,在每次測試之前調用setUp()。 所以這是平常的行爲,與特質無關。 試試這個:

public static function setUpBeforeClass() 
{ 
    $this->getContainer(); 
    echo "it's called once a class"; 
} 

protected function setUp() 
{ 
    $this->getContainer(); 
    echo "it's called before each test"; 
} 

爲特徵的真正區別,當你想使用它的方法,數據提供商開始。 您可能會遇到一個錯誤,該方法未知,因爲數據提供程序在構造函數之前加載。 這將失敗

class EditVoterTest extends TestCase 
{ 
    use ContainerAwareTrait; 

    /** 
    * @dataProvider getData 
    */ 
    public function testSomething() 
    { 
     // test something 
    } 

    public function getData() 
    { 
     return $this->getContainer(); 
    } 
}