先看一個例子:testPush 和 testPop 都依賴 testEmpty。
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class StackTest extends TestCase
{
public function testEmpty(): array
{
$stack = [];
$this->assertEmpty($stack);
return $stack;
}
/**
* @depends testEmpty
*/
public function testPush(array $stack): array
{
array_push($stack, 'foo');
$this->assertSame('foo', $stack[count($stack)-1]);
$this->assertNotEmpty($stack);
return $stack;
}
/**
* @depends testEmpty
*/
public function testPop(array $stack): void
{
$this->assertSame('foo', array_pop($stack));
$this->assertEmpty($stack);
}
}
那么,testEmpty 會執(zhí)行幾次呢?答案是1次。這意味著對象的狀態(tài)在三個測試中共享,如果在 testPush 和 testPop 中保持只讀訪問,是okay的。否則有三種選擇:
@depends clone@depends shallowClone- 不用
@depends
如果 clone 能解決問題的話,就再好不過了。否則就放棄吧,提前一個公用的方法出來,不要用 @depends 了。