EventListeners vs. Trivial Sagas and Testing


I currently encountered the following situation:

In several places in my domain, there are very small processes where EventX from Aggregate A has to trigger CommandY for Aggregate B.

So, I ended up with some Saga which had only methods which were @StartSaga @EndSaga … and maybe a chain of these.

Now for me this appears to be inefficient, as instantiating Sagas for this purpose is relatively costly.

You can implement this behaviour, where there is no stateful process more resource efficient in a singleton @Service with @EventListeners

Works like a charm.

The problem comes in when you want to du unit tests of the EventListeners. Basically, you want similar capabilities as in the Saga test fixture
where you want to inspect if the resulting commands of the event handler.

You cannot use the fixtures for aggregates, and you cannot use the saga fixture for this. Currently we inject a RecordingCommandBus and
manually check the resulting commands after directly calling the event handler.

To the questions:

  • Is this not supported in the test fixtures because doing this kind of behaviour in an event listener is a bad idea and should not be done? If so, why?
  • Should we use Sagas for this instead?
  • If this is fine, is there a recommended way to test these with the existing fixtures? Currently the tests feel a bit “hacky” to me.

Thank you.

Best regards,

Hi Dominic,

it is in fact good practice to just use @Service (or @Component, actually) with @EventListeners if your sagas always end with the method that started them. It’s an indication that you don’t need any state in between events.

The fact that there is no explicit test fixture for it, is that you’re just testing the behavior of a pretty standard component. It’s pretty easy to inject mocks and unit test it.