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
爲什麼容器「構建「 每一次 ?
我認爲,對於每一個測試,正在創建測試類的新實例。 –
對於每個測試,PHPUnit將運行'setUp()' –
正如@FelippeDuarte所說,'setUp'是設計用於在執行任何測試(實例化對象,連接資源等)之前完成所有必要事情的方法。所以,作爲單元測試的手段,每個測試都必須被認爲是唯一的,因此每個測試都必須執行'setUp'。 –