基於您的事件機制的實施。由手動發送該事件
1)測試提醒,發送腳本:像,當你的代碼中的一些事件偵聽器的地方接收事件user:reminder
使用用戶ID,那麼你只需要
$eventBus->init();
$eventBus->attachListener($reminderListener);
$eventBus->fire(new ReminderEvent($user->id));
$this->expect(...); // reminder must be `sent`
2)測試生成事件的時候時間已經過去了:
$time = now();
$delay = ...;
$emitter = new RemindEventEmitter($user->id, $time + $delay)
$eventBus->addEmitter($emitter);
$eventBus->setCurrentTime($time); // when we just registered emitter...
$eventBus->run();
$this->expectNot(...); // ... that event _must not_ be fired
$eventBus->setCurrentTime($time + $delay); // manually skip $delay time ...
$eventBus->run();
$this->expect(...); // test that event _must_ be fired
這事件產卵/(在我的例子$eventBus
)分派的事情必須在中繼mockable /更換的時間拼命三郎:
// in production code
$eventBus->setCurrentTime(now());
// elsewhere in tests
$eventBus->setCurrentTime(<point in time you want to test against>);
優秀的答案。我使用Laravel/PHPUnit,Laravel使用Carbon來處理日期 - 你的回答讓我從Carbon中找到以下代碼片斷:'Carbon :: setTestNow(Carbon :: now() - > addDay(3));'' – Chris