日期有關(guān)的代碼是比較難測(cè)試的,超時(shí)30分鐘防嗡,不能真的等30分鐘债沮。在 php 生態(tài)中,個(gè)人覺得 ClockMock
是最好用的本鸣,
- Mock的日期功能最全面,
- 直接替換系統(tǒng)接口硅蹦,不依賴中間接口做隔離
ClockMock
是 Symfony phpunit bridge 中的一部分荣德,在非 Symfony 項(xiàng)目中也可以使用。在標(biāo)準(zhǔn)的phpunit
中使用時(shí)童芹,需要注冊(cè)test-listener
涮瞻,修改 phpunit
的配置文件:
<!-- http://phpunit.de/manual/6.0/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.0/phpunit.xsd"
>
<!-- ... -->
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener"/>
</listeners>
</phpunit>
Mock 了 time(), microtime(), sleep(), usleep() gmdate()
系統(tǒng)函數(shù)。絕大多數(shù)時(shí)間操作都來自于這些函數(shù)假褪,所以使用第三方庫的代碼也可以測(cè)試署咽。
它的內(nèi)部實(shí)現(xiàn)原理是:調(diào)用函數(shù)時(shí),如果這個(gè)函數(shù)已經(jīng)定義在了當(dāng)前的 namespace 中,則調(diào)用這個(gè)函數(shù)宁否,否則調(diào)用全局函數(shù)窒升。
``ClockMock::register(MyClass::class);實(shí)際的作用是通過
eval()在
MyClass::class` 所在的 namespace 中注入這些時(shí)間函數(shù)。
// the test that mocks the external time() function explicitly
namespace App\Tests;
use App\MyClass;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ClockMock;
/**
* @group time-sensitive
*/
class MyTest extends TestCase
{
public function testGetTimeInHours()
{
ClockMock::register(MyClass::class);
$my = new MyClass();
$result = $my->getTimeInHours();
$this->assertEquals(time() / 3600, $result);
}
}
需要注意的是:當(dāng)函數(shù)在注入前慕匠,已經(jīng)在所在的 namespace 中調(diào)用饱须,則 php 執(zhí)行引擎使用已經(jīng)調(diào)用過的(全局函數(shù)),而不理會(huì)
新注入的函數(shù)(也許是性能考慮)台谊。所以靠譜的辦法是修改 phpunit.xml :
<phpunit bootstrap="./tests/bootstrap.php" colors="true">
<!-- ... -->
<listeners>
<listener class="\Symfony\Bridge\PhpUnit\SymfonyTestsListener">
<arguments>
<array>
<element key="time-sensitive">
<array>
<element key="0">
<string>Namespace\Need\Mocked1</string>
</element>
<element key="1">
<string>Namespace\Need\Mocked2</string>
</element>
</array>
</element>
</array>
</arguments>
</listener>
</listeners>
</phpunit>
這樣在測(cè)試開始運(yùn)行前蓉媳,提前注入到相關(guān)的 namespace 中。
Mock掉的時(shí)間锅铅,默認(rèn)是 TestFixture 開始的時(shí)間酪呻,也可以手工調(diào)用 ClockMock::withClockMock(100)
強(qiáng)制到某個(gè)已知值,當(dāng)通常并沒有這個(gè)必要盐须。