Testing Domain Events

You already know how to publish Domain Events, but how can you unit test this and ensure that UserRegistered is really fired? The easiest way we suggest is to use a specific EventListener that will work as a Spy to record whether or not the Domain Event was published. Let's see an example of the User Entity unit test:

use DddDomainDomainEventPublisher;
use DddDomainDomainEventSubscriber;

class UserTest extends PHPUnit_Framework_TestCase
{
// ...

/**
* @test
*/
public function itShouldPublishUserRegisteredEvent()
{
$subscriber = new SpySubscriber();
$id = DomainEventPublisher::instance()->subscribe($subscriber);

$userId = new UserId();
new User($userId, '[email protected]', 'password');
DomainEventPublisher::instance()->unsubscribe($id);

$this->assertUserRegisteredEventPublished($subscriber,$userId);
}

private function assertUserRegisteredEventPublished(
$subscriber, $userId
) {
$this->assertInstanceOf(
'UserRegistered', $subscriber->domainEvent
);
$this->assertTrue(
$subscriber->domainEvent->serId()->equals($userId)
);
}
}

class SpySubscriber implements DomainEventSubscriber
{
public $domainEvent;

public function handle($aDomainEvent)
{
$this->domainEvent = $aDomainEvent;
}

public function isSubscribedTo($aDomainEvent)
{
return true;
}
}

There are some alternatives to the above. You could use a static setter for the DomainEventPublisher or some reflection framework to detect the call. However, we think the approach we've shared is more natural. Last but not least, remember to clean up the Spy subscription so it won't affect the execution of the rest of the unit tests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset