vendredi 4 décembre 2015

How can I unit test a method that dispatches events that alter behavior of the method under test?

I have a custom event that has a public property:

class MyCustomEvent
{
    public $allowAction = false;
}

I have a class that creates this event, and dispatches an event with the event object, allowing event listeners/subscribers to change the property on the object.

class MyBizLogic
{
    private $dispatcher;

    public function __construct(EventDispatcher $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    public function doSomething()
    {
        $event = new MyCustomEvent();
        $dispatcher = $this->dispatcher->dispatch('my_custom_event', $event);
        if ($event->allowAction) {
            // do action
        } else {
            // do something else
        }
    }
}

How can I unit test doSomething? I need a way to control the properties of the event object, but the event object is not a dependency I can mock. It's created within the method I'm testing.

I don't think this is a design smell, since this is how imagine most developers dispatch events. What can I do here to properly test the different outcomes that doSomething should deal with?

Aucun commentaire:

Enregistrer un commentaire