Unit testing Aggregates without fixture

Hello,

Using Axon 3.1, I’d like to perform unit tests on aggregates by invoking methods directly on the aggregate and assert on the generated events.
I cannot annotate the command on the aggregate since it’s a generated code and I cannot add @TargetAggregateIdentifier
In any case, I rather use CommandHandlers that load and invoke methods on the aggregate.

In short, how can I unit test the aggregate by invoking it’s methods and assert on generated events?
(I was able to do so with Axon 2.4.x, where the aggregate used to inherit from AbstractAnnotatedAggregateRoot

Thanks for the help,
Harel

Hi Harel,

if you can’t use @TargetAggregateIdentifier, you can still define your own CommandTargetResolver. The default behavior is to look for @TargetAggregateIdentifier annotated fields or methods, but you can choose any strategy you like. You can define it on the AggregateConfigurer instance for your Aggregate.

But that probably won’t address your need to test your aggregate in isolation. If you use JUnit, you can define a Rule, which will make sure the aggregate has access to the AggregateLifecycle.apply() logic. Just define a field (JUnit requires them to be public) like so:

@Rule
public StubAggregateLifecycleRule lifecycle = new StubAggregateLifecycleRule();

This lifecycle gives you access to all events that have been applied by your aggregate. Note that it doesn’t cause the @EventSourcingHandler methods to be called.

If you’re not on JUnit, you can use the StubAggregateLifecycle class, and use the activate() and close() methods in the scope of your tests.

Hope this helps.
Cheers,

Allard