Video Tutorial Testing an EventSubscriber

The EventSubscriber are not necessarily complex classes to test. They act as simple services with the particularity of defining the events to which they subscribe.

The objective of the tests will therefore be to verify that the class subscribes to the right events and calls the methods in the expected order.

We can start by simply checking that our event is listed in the subscription table.

public function testEventSubscription () {
    $ this-> assertArrayHasKey (ExceptionEvent :: class, ExceptionSubscriber :: getSubscribedEvents ());

But a more solid approach will be to use the dispatcher to verify that the event is properly captured and processed.

To test the following code for example:

// We mock the services on which the class depends
$ mailer = $ this-> getMockBuilder ( Swift_Mailer :: class) -> disableOriginalConstructor () -> getMock ();
$ Mailer-> Expects ($ this-> ounce ()) -> method ( 'send');

// We create our subscriber
$ subscriber = new ExceptionSubscriber ($ mailer);

// We create our event
$ kernel = $ this-> getMockBuilder (KernelInterface :: class) -> getMock ();
$ event = new ExceptionEvent ($ kernel, new Request (), 1, new  Exception ('Hello world'));

// We dispatch our event by having our subscriber in the dispatcher.
$ dispatcher = new EventDispatcher ();
$ Dispatcher-> addSubscriber ($ subscriber);
$ Dispatcher-> dispatch ($ event);

For the rest (the business logic of your subscriber), the test will be written like any PHP class.