In memory event store

Ben Smith edited this page Sep 2, 2018 · 10 revisions

Commanded provides an in-memory event store implementation, for test use only, in the module Commanded.EventStore.Adapters.InMemory. This is a transient event store without persistence.


Ensure you configure the in-memory adapter in your environment config file, config/test.exs:

config :commanded,
  event_store_adapter: Commanded.EventStore.Adapters.InMemory

You will need to start the in-memory event store in your test/test_helper.exs file:

alias Commanded.EventStore.Adapters.InMemory
alias Commanded.Serialization.JsonSerializer

{:ok, _pid} = InMemory.start_link(serializer: JsonSerializer)


You may replace or omit the serializer configuration. By including it here we ensure events used by the tests can be successfully serialized and deserialized.


ExUnit case template

You can use ExUnit's case template feature to restart the in-memory event store for each test run.

defmodule InMemoryEventStoreCase do
  use ExUnit.CaseTemplate

  alias Commanded.EventStore.Adapters.InMemory

  setup do
    on_exit(fn ->
      :ok = Application.stop(:my_app)


      {:ok, _apps} = Application.ensure_all_started(:my_app)

Replace both occurrences of :my_app in the above ExUnit case template with the name of your own application.

The reason why your app must be stopped and then started between resetting the event store is to ensure all application processes are restarted with their initial state to prevent state from one test affecting another.

Use the InMemoryEventStoreCase module within any test files that need to use the event store.

defmodule ExampleTest do
  use InMemoryEventStoreCase

  # Define your tests here ...

Running your tests

Run mix test as usual to execute the tests using the in-memory event store.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.