Skip to content
Advertisement

How to add test to Manually Registering Events Listener in laravel?

I have a manually registering event and related listener. For this i want to add test so i checked laravel Mocking Test in documentation but i didn’t find any way to test manually registering event with parameter listener. So anyone help me how to do this? Below i attached working related code.

Event is calling in the TeamObserver deleting method like below

class TeamObserver
{
    public function deleting(Team $team)
    {
    event('event.team.deleting', array('team' => $team));
    }
}

Event and Listeners are registered in EventServiceProvider boot method like below

public function boot()
{
    parent::boot();
    Event::listen(
        'event.team.deleting',
        'ListenersTeamDeletingListener'
    );
}

TeamDeletingListener is look like below

class TeamDeletingListener
{
    public function handle($team)
    {
        Log::info('Deleting Inventory Module');
        Log::info($team);
    }
}

Advertisement

Answer

The simplest way to do this, is to replace the real implementation of your listener with a mocked one. Here’s an example test. It will fail if you remove event('event.team.deleting', array('team' => $team)); or pass a different team. If I got you right, that’s what you want to achieve.

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,
        function (MockInterface $mock) use ($team) {
            // Expectation
            $mock->shouldReceive('handle')
                ->with($team)
                ->once();
        }
    );

    // Delete team
    $team->delete();
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement