https://phpunit.de/manual/current/en/test-doubles.html
真的對phpunit的官網文件有障礙,看不太懂,但先努力把它中文化,日後應該可以派上用場。
test doubles,模擬物件,就是有些類別在測試環境根本不能被實例化,像是第3方的API,就用一個假的來代替,and then,通過測試,這樣吧。
Stubs:模擬的物件能夠定義真實物件函數的返回值,稱為Stub 。
返回固定值:Stub預定的返回值都是null,底下的code,雖然$stub以createMock()模擬了Mock類別,直接執行::doReturnValue()並不會返回bar,而是null。必須用method指定要被模擬的函數,willReturn設定函數要返回多少值。willReturn($value)也等於will($this->returnValue($value))。
/** src/Mock.php */
class Mock
{
public function doReturnValue($arg = null)
{
return 'bar';
}
}
/** tests/src/StubTest.php */
use PHPUnit\Framework\TestCase;
class StubTest extends TestCase
{
public function testReturnValue()
{
//模擬實例化物件
$stub = $this->createMock(Mock::class);
$var = $stub->doReturnValue(); // return null
//指定doReturnValue函數返回foo
$stub->method('doReturnValue')
->willReturn('foo');
$this->assertEquals('foo', $stub->doReturnValue());
}
}
Continue reading “PHPUnit – Test Doubles” →