Testing new aggregate creation with ID value

Hopefully a quick question – I have a command (enroll) which creates a new Enrollment aggregate and fires an EnrollmentEvent. It seems to me that the caller of the command shouldn’t need to worry about the enrollmentId as that can be created by the commandHandler or aggregate constructor.

However, in testing, I am required to “know” the enrollmentId to create an event to compare to.

public void testFirstEnroll() {
    DateTime startDate = new DateTime(2015, 1, 1, 0, 0);
    DateTime endDate = new DateTime(2016, 1, 1, 0, 0);
    DateTime eventDate = DateTime.now();
            .when(new EnrollCommand("ClientId1", "Fred", "medical", "insurance-1", startDate, endDate, eventDate))
            .expectEvents(new EnrollEvent("ClientId1", "965201A1-2738-42CC-832A-54E896150095", "Fred", "medical", "insurance-1", startDate, endDate, eventDate));

I feel there’s something reasonably obvious that I’m missing, either in terms of crafting a matcher or that the command caller will have to provide an ID for a new aggregate.

Thanks, Tim

Hi Tim,

The aggregate is generally not interested in the value of its identifier. The identifier is used by the ‘world outside the aggregate’ to identify the aggregate. As such it makes sense that the identifier is created in this outside world as well, usually by the component that issues the command.

There are other reasons this is advantageous as well. You already identified that it makes testing easier but there is also a performance benefit. It is good practice to have the aggregate handle commands as quickly as possible. The reason for this is that expensive operations (like going to a database) temporarily block access to the aggregate instance for subsequent commands. While the time it takes to create a good identifier is short it is still relatively expensive and as such should be avoided and done outside the aggregate.