Skip to content

Testing

Testing is a key part of building reliable systems – and with CQRS and Event Sourcing, how you test changes just as much as how you build.

You're no longer testing a traditional CRUD service. You're testing behavior, decisions, and outcomes – as expressed through commands and events.

Testing the Write Side

The write side is where decisions are made. A command comes in, business logic runs, and one or more events are produced.

The natural way to test this is using a Given–When–Then pattern:

  • Given a history of past events (reconstructing the current state)
  • When a command is handled
  • Then expect specific new events

Example

Imagine a library member has already borrowed 5 books:

Given:
- BookBorrowed (bookId: "b-1001")
- BookBorrowed (bookId: "b-1002")
- BookBorrowed (bookId: "b-1003")
- BookBorrowed (bookId: "b-1004")
- BookBorrowed (bookId: "b-1005")

When:
- BorrowBook (bookId: "b-1006")

Then:
- Expect: TooManyBooksBorrowedError

This kind of test helps you validate domain rules directly. You're not testing persistence, you're testing decisions.

Testing the Read Side

The read side is based on projections: components that listen to events and update read models accordingly.

Here, tests usually follow a simpler structure:

  • Given an empty state
  • When a series of events is applied
  • Then assert the state of the read model

Projections are often pure functions (event in, state out), which makes them very testable.

Testing Process Managers and Reactions

Some components, like process managers or event handlers, react to events by triggering commands or emitting side effects (emails, tasks, etc.).

These should be tested by:

  • Feeding in events
  • Asserting the resulting commands or actions

This helps you test reactive flows and ensure that multi-step processes behave as expected.

Why This Matters

With Event Sourcing, the system is entirely driven by events – which also means:

  • All inputs and outputs are explicit
  • State is fully controlled
  • Tests can simulate any scenario by controlling event history

This makes CQRS and Event Sourcing very testable by design – as long as you keep business logic in the right place.

Next up: Learn how to handle long event streams and improve performance with Snapshots and Performance.