Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active February 21, 2022 21:52
Show Gist options
  • Save james2doyle/0ff7eba9bf11e50c063f3453c802f0f9 to your computer and use it in GitHub Desktop.
Save james2doyle/0ff7eba9bf11e50c063f3453c802f0f9 to your computer and use it in GitHub Desktop.
Testing that an event listener was called in Laravel without additional frameworks
<?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.');
@tkivelip
Copy link

Nice solution, thanks :)

@mbryne
Copy link

mbryne commented Apr 13, 2021

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