The EventSpyTestTrait is used for tests that want to assert various events are fired.
PSR Event Dispatcher
The event manager allows firing of PSR-14 compliant events for newer things like ResourceEvents.
Vanilla offers a few utilities to test them
clearDispatchedEvents()
- Clear any previously dispatched events. Automatically run between tests.assertNoEventsDispatched()
- Assert that no events were dispatched.assertEventsDispatched($events)
and assertEventDispatched($event)
- assert resource events were dispatched.
Vanilla Event Handlers
Vanilla has it's own event firing system that is used across it's 10 years of code. These can be tested using the following methods.
assertEventFired()
- Assert an event was fired.clearFiredEvents()
- Clear all fire events. Automatically run between tests.assertHandlerCalled($name)
- Assert that an event handler was called.clearCalledHandlers()
- Clear the called handlers.handlerCalled()
- Mark an event handler as called.
Example
Here's some example usage. There are a few notable things:
- You can apply assertions about the arguments passed to the event.
- You can receive the arguments that were passed to the event.
- You can write event handlers on your test class, and they will be automatically bound.
/**
* Test that date times in the database get updated.
*/
public function testUpdateActiveDate() {
$user = $this->createUser();
$this->visitUpdater()->updateVisit($user['userID']);
// Ensure that events are fired.
$this->assertHandlerCalled('userModel_visit_handler', [
new IsInstanceOf(\UserModel::class),
new IsType('array'),
]);
// Ensure that events are fired.
$calledArgs = $this->assertHandlerCalled('userModel_updateVisit_handler', [
new IsInstanceOf(\UserModel::class),
new IsType('array'),
]);
$this->assertEquals([
'DateLastActive' => DateTimeFormatter::timeStampToDateTime($updatedTime->getTimestamp()),
'CountVisits' => 1,
], $calledArgs[1]['Fields']);
}
/**
* Test handler.
*
* @param array $args
*/
public function userModel_visit_handler(...$args) {
$this->handlerCalled(__FUNCTION__, $args);
}
/**
* Test handler.
*
* @param array $args
*/
public function userModel_updateVisit_handler(...$args) {
$this->handlerCalled(__FUNCTION__, $args);
}