Support the ongoing development of Laravel.io →
posted 9 years ago
Testing

Hi, everyone! Have the following issue for more a while now and can't find an answer - I'm trying to test Event Listener in Laravel. This is my listener:

class FlashNotifier
{

    public function handleMenuItemWasStored()
    {
        Session::flash('flash-status', 'success');
        Session::flash('flash-message', 'Item was stored.');
    }

    public function subscribe($events)
        {
            $events->listen(
            MenuItemWasStored::class,
            '\App\Listeners\Menu\FlashNotifier@handleMenuItemWasStored'
        );
    }
}

This is my test:

public function testEventListenerWasTriggered()
{
    $listener = Mockery::mock('App\Listeners\Menu\FlashNotifier');
    $d = new Dispatcher;
    $listener->shouldReceive('handleMenuItemWasStored')->once();
    $d->fire('App\Events\Menu\MenuItemWasStored');
}

Which gets the following exception:

 1) FlashListenerTest::testEventListenerWasTriggered
 Mockery\Exception\InvalidCountException: Method handleMenuItemWasStored() from     Mockery_1_App_Listeners_Menu_FlashNotifier should be called
 exactly 1 times but called 0 times.

What is it that I'm doing wrong here?

Last updated 3 years ago.
0

It took me a while to figure it out, so here is how I solved it:

public function testEventListenerWasTriggered()
{
    $listener = new FlashNotifier();
    $listener->handleMenuItemWasStored();

    $this->assertSessionHas('flash-status', 'success');
    $this->assertSessionHas('flash-message', 'Item was stored.');
}  
Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.