Testing events (mocking?) in codeception


(Simonnouwens) #1

Hi,

We are writing quite a large project involving event-triggered actions (e.g. emails after registration) which we would like to test with codeception. I haven’t been able to find documentation nor source code that helps with testing of events, and I’m not sure what the best way is to proceed. Laravel in example has some helper functions:

https://laravel.com/docs/5.1/testing#mocking-events

It shouldn’t be to hard to manually create something like that for yii2 (which would be wasted effort if it already exists, which is question 1: does yii2 has some helpers for testing events :) ). The second point is the responsibility: lets say there is some custom event that is triggered once a user status changes, which is used by the email module. Who’s responsible for testing that the event is actually triggered? Leaving it up to the user module might cause a problem if the event is changed somewhere in the future: the email will silently fail simply because the event is not triggered anymore, which might not be noticed by a dev. responsible for just the user module.

Alternatively, creating a whole (complex) user object in the mail module just to check whether an event is triggered isn’t ideal as well.

Any suggestions? :) THanks in advance!


(Jacob Moen) #2

Both Laravel and Yii uses Codeception so you should be able to mock your heart out. :)

AspectMock is a Codeception sister project: https://github.com/C...tion/AspectMock

(( I haven’t used it myself yet, unfortunately, so I am not able to assist directly ))

Edit:


(Simonnouwens) #3

Thank you for your reply jacmoe :)

What we ended up doing (if anybody is interested) was register event listeners in the test, executing the required action and see if the event triggered, pretty straight forward!




\yii\base\Event::on(User::className(), ActiveRecord::EVENT_BEFORE_INSERT,

            function ($event) use (&$num_before_insert_triggers) {

                $num_before_insert_triggers += 1;

            });