Last active
February 21, 2022 21:52
-
-
Save james2doyle/0ff7eba9bf11e50c063f3453c802f0f9 to your computer and use it in GitHub Desktop.
Testing that an event listener was called in Laravel without additional frameworks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// overall test answer | |
$was_called = false; | |
$this->app->resolving(function ($object, $app) use (&$was_called) { | |
if ($object instanceof MyEventListener) { | |
// the object was resolved at one point | |
$was_called = true; | |
} | |
}); | |
// do something that invokes the listener | |
// let us know the state - call a custom failed message if false | |
$this->assertTrue($was_called, MyEventListener::class . ' was not called.'); |
Cheers for this, this also led me to the solution found at this StackOverflow link,
here:
public function testTeamDeletion()
{
// Persist team that should be deleted
$team = new Team();
$team->name = 'My Team';
$team->save();
// Mock the listener
$this->mock(
TeamDeletingListener::class, // expected class
function (MockInterface $mock) {
$mock->shouldReceive('handle')->once();
}
);
// Delete team
$team->delete();
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice solution, thanks :)