I have a small system that uses Jonathan Oliver's CommonDomain and EventStore.
How can I unit test my aggregate roots in order to verify that correct events are raised?
Consider following aggregate root:
public class Subscriber : AggregateBase
{
private Subscriber(Guid id)
{
this.Id = id;
}
private Subscriber(Guid id, string email, DateTimeOffset registeredDate)
: this(id)
{
this.RaiseEvent(new NewSubscriberRegistered(this.Id, email, registeredDate));
}
public string Email{ get; private set; }
public DateTimeOffset RegisteredDate { get; private set; }
public static Subscriber Create(Guid id, string email, DateTimeOffset registeredDate)
{
return new Subscriber(id, email, registeredDate);
}
private void Apply(NewSubscriberRegistered @event)
{
this.Email = @event.Email;
this.RegisteredDate = @event.RegisteredDate;
}
}
I would like to write a following test:
// Arrange
var id = Guid.NewGuid();
var email = "[email protected]";
var registeredDate = DateTimeOffset.Now;
// Act
var subscriber = Subscriber.Create(id, email, registeredDate);
// Assert
var eventsRaised = subscriber.GetEvents(); <---- How to get the events?
// Assert that NewSubscriberRegistered event was raised with valid data
I could set up whole EventStore with memory persistence and synchronous dispatcher, hook up mock event handler and store any published events for verification, but it seems a bit of overkill.
There is an interface IRouteEvents
in CommonDomain. Looks like I could mock it to get the events directly from AggregateBase
but how would I actually pass it to my Subscriber
class? I don't want to 'pollute' my domian with testing-related code.
I've found out that
AggregateBase
explicitly implementsIAggregate
interface, which exposesICollection GetUncommittedEvents();
method.So the unit test looks like that:
var eventsRaised = ((IAggregate)subscriber).GetUncommittedEvents();
and no dependency on EventStore is required.