Testing AggregateLifecycle.createNew() when created aggregate needs a resource

Hi,
I am having issues with testing an aggregate that creates another aggregate.

@Aggregate
class Foo {
    Id id;
    Id barId;

    @CommandHandler
    void handle(DoIt command) throws Exception {
        apply(new Done(id, createNew(Bar.class, () -> new Bar(id)).invoke(Bar::getId)));
    }

    @EventSourcingHandler
    void on(Done event) {
        barId = event.getBarId();
}

@Aggregate
class Bar {
    @Getter
    Id id;
    Id fooId;
    MyComponent delegate;

    Bar(Id fooId) {
       apply(new Created(new Id(), fooId));
    }

    @EventSourcingHandler
    void on(Created event, MyComponent comp) {
       id = event.getId();
       fooId = event.getFooId();
      delegate = comp;
    }
}     

The test looks similar to

@Test
void whenDoIt_thenBarCreated_andDone() {
   new AggregateTestFixture<>(Foo.class)
      .registerInjectableResource(new MyComponent())
      .given(new FooCreated(new Id("foo1"))
      .when(new DoIt(new Id("foo1"))
      .expectEvents(new Done(new Id("foo1")), new Created(new Id("bar1"), new Id("foo1")));
}

Even though MyComponent is explicitly registered as a resource, the event handler on Bar does not get invoked because of a missing resource for its parameter.

I like the idea of simply dispatching a command to the first aggregate, which creates another aggregate prefilling it with its data. This approach seems a lot easier to implement than doing it with a saga, which in turn would require some intermediate event.

Thank you for any idea :slight_smile:

P.S. The first aggregate also requires injected resources, and these are correctly resolved.

Hi David,

The issue is that the component is registered on the Foo aggregate class because the test fixture is created for the Foo aggregate. It could work if you add the Mycomponent to the signature of the Bar class constructor and set the delegate there.

I hope this helps,

Yvonne

Hi Yvonne,
thanks for the reply. I’ve rewritten the code into a saga to keep the two aggregates decoupled.

David