Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing listeners in Laravel 5.1

Is there an standard way to unit test Listeners in Laravel 5.1 (not mocking the Event::fire()) or do you just instantiate it, call handle() with mocked params and make assertions, the oldschool way?

I read Events and Testing and it doesn't really says anything about unit testing listeners.

like image 378
Christopher Francisco Avatar asked Aug 13 '15 00:08

Christopher Francisco


People also ask

How do you test event listeners?

You can test the event listener does its thing by instantiating the listener, then getting it to handle your event. // Create a listener instance. $listener = app()->make(YourListener::class); // or just app(YourListener::class) // Create an event instance.

What are listeners in Laravel?

Laravel provides a simple mechanism for events and listeners so that whenever you want to subscribe or listen to any event of your application, you can do it easily. You can register events with their listeners and decide what you want them to do after a particular action.


1 Answers

AFAIK it's totally up to you and your preferences. You could do either of the two approaches mentioned, but I actually don't test them at all. Instead I try to have only a very basic code in the Listener, and move all the logic into separate services. IMHO that makes code easier to understand and cleaner to unit test without mocking the hell out of it.

like image 150
ivanhoe Avatar answered Oct 04 '22 02:10

ivanhoe