Akashic Help

Testing with the in-memory backend

The in-memory backend ships in akashic-core and implements the same contract as PostgreSQL and KurrentDB. Tests written against it need no containers and run in milliseconds.

Test the decider and evolver directly

Deciders and evolvers are plain functions of their inputs. Most domain rules can be tested with no backend at all:

class AccountDeciderTest { private val open = AccountState(aggregateId = "acc-1", owner = "Ada", balance = 100) @Test fun `opening an account proposes Opened`() { runBlocking { val decision = AccountDecider.decideFirst(AccountCommand.Open("Ada")) assertThat(decision).isEqualTo(FirstEventDecision.Accepted(AccountEvent.Opened("Ada"))) } } @Test fun `a withdrawal beyond the balance is rejected`() { runBlocking { val decision = AccountDecider.decideExisting(open, AccountCommand.Withdraw(101)) assertThat(decision).isEqualTo(EventDecision.Rejected("Insufficient funds")) } } }

Test command handling

InMemoryProvider builds the same services the production providers do. Each provider instance has its own storage, so creating one per test class isolates tests from each other:

class AccountServiceTest { private val accounts = InMemoryProvider().aggregateService(AccountDefinition) @Test fun `commands change committed state`() { runBlocking { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) accounts.handle(AccountCommand.Deposit(100).forAccount("acc-1")) val result = accounts.handle(AccountCommand.Withdraw(30).forAccount("acc-1")) assertThat(result).isInstanceOf(AggregateChangeResult.Success.Applied::class) val found = accounts.getById("acc-1") as AggregateLookupResult.Found assertThat(found.committedState.state.balance).isEqualTo(70) assertThat(found.committedState.version).isEqualTo(2) } } @Test fun `a rejected command leaves the stream untouched`() { runBlocking { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) val result = accounts.handle(AccountCommand.Withdraw(1).forAccount("acc-1")) assertThat(result).isEqualTo(AggregateChangeResult.Failure.Rejected("Insufficient funds")) val found = accounts.getById("acc-1") as AggregateLookupResult.Found assertThat(found.committedState.version).isEqualTo(0) } } @Test fun `repeating an accepted command with nothing to change writes nothing`() { runBlocking { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) val result = accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) assertThat(result).isInstanceOf(AggregateChangeResult.Success.NoChange::class) } } }

Handling goes through the real codec, so a converter that loses a field fails here as well as in codec tests.

Test a subscriber without a runner

onEvents is a function too. Build a SubscriptionBatch from committed events and call it. Calling it twice with the same batch is the simplest test of replay safety:

class TransferProcessorTest { private val accounts = InMemoryProvider().aggregateService(AccountDefinition) private val processor = TransferProcessor<CheckpointLong>(accounts) { "checkpoint:${it?.id ?: "beginning"}" } @Test fun `a redelivered batch credits the receiving account once`() { runBlocking { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) accounts.handle(AccountCommand.Open("Grace").forAccount("acc-2")) accounts.handle(AccountCommand.Deposit(100).forAccount("acc-1")) val sent = accounts.handle(AccountCommand.SendTransfer("acc-2", 40).forAccount("acc-1")) as AggregateChangeResult.Success.Applied val batch = SubscriptionBatch( events = sent.events.map { SubscriptionEvent(CheckpointLong(it.version), it) }, precedingCheckpoint = CheckpointLong(1), ) processor.onEvents(batch) processor.onEvents(batch) val receiver = accounts.getById("acc-2") as AggregateLookupResult.Found assertThat(receiver.committedState.state.balance).isEqualTo(40) } } }

Test the whole application

Write the application against BackendProvider, and a test can run all of it, runners included, in memory:

class AccountApplicationTest { private val backend = InMemoryProvider() private val application = AccountApplication(backend) { checkpoint: CheckpointLong? -> "checkpoint:${checkpoint?.id ?: "beginning"}" } private val accounts = application.accounts private suspend fun balanceOf(accountId: String): Long = (accounts.getById(accountId) as AggregateLookupResult.Found).committedState.state.balance @Test fun `the balance projection follows committed events`() { runBlocking { application.start() try { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) val deposited = accounts.handle(AccountCommand.Deposit(100).forAccount("acc-1")) as AggregateChangeResult.Success waitForVersion(version = deposited.committedState.version) { application.balances.balanceOf("acc-1")?.version } assertThat(application.balances.balanceOf("acc-1")?.balance).isEqualTo(100) } finally { application.close() } } } @Test fun `a transfer reaches the receiving account`() { runBlocking { application.start() try { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) accounts.handle(AccountCommand.Open("Grace").forAccount("acc-2")) accounts.handle(AccountCommand.Deposit(100).forAccount("acc-1")) accounts.handle(AccountCommand.SendTransfer("acc-2", 40).forAccount("acc-1")) // Opened is version 0; the deposit and its idempotency event are versions 1 and 2. waitForVersion(version = 2) { application.balances.balanceOf("acc-2")?.version } assertThat(balanceOf("acc-1")).isEqualTo(60) assertThat(balanceOf("acc-2")).isEqualTo(40) } finally { application.close() } } } @Test fun `a transfer to an account that is not open is refunded`() { runBlocking { application.start() try { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) accounts.handle(AccountCommand.Deposit(100).forAccount("acc-1")) accounts.handle(AccountCommand.SendTransfer("missing", 40).forAccount("acc-1")) // Versions: Opened 0, Deposited 1, TransferSent 2, refund 3, its idempotency event 4. waitForVersion(version = 4) { application.balances.balanceOf("acc-1")?.version } assertThat(balanceOf("acc-1")).isEqualTo(100) } finally { application.close() } } } @Test fun `the maintainer writes a snapshot that matches history`() { runBlocking { application.start() try { accounts.handle(AccountCommand.Open("Ada").forAccount("acc-1")) repeat(50) { accounts.handle(AccountCommand.Deposit(1).forAccount("acc-1")) } val snapshots = backend.snapshotStore(AccountDefinition, AccountStateSchemaCurrent) // AccountSnapshots takes a snapshot every 50 versions, never at version 0: Opened is // version 0 and the fiftieth deposit is version 50. waitForVersion(version = 50) { snapshots.load("acc-1")?.version } val operations = SnapshotMaintenanceOperations( aggregate = AccountDefinition, stateSchema = AccountStateSchemaCurrent, eventStore = backend.aggregateStore(AccountDefinition), snapshotStore = snapshots, ) assertThat(operations.verify("acc-1")).isEqualTo(SnapshotVerificationResult.Valid(50)) } finally { application.close() } } } }

Subscriptions are asynchronous, so these tests wait for an observable result. waitForVersion polls every 10 milliseconds and fails after 10 seconds. The in-memory source polls for new events every 5 milliseconds.

Always close runners and sources, in that order, even when the test fails.

Share storage between providers

To simulate two instances of an application over one store, give two providers the same storage objects:

val events = InMemoryEventStorage() val snapshots = InMemorySnapshotStorage() val checkpoints = InMemoryCheckpointStorage() val instanceA = InMemoryProvider(events, snapshots, checkpoints) val instanceB = InMemoryProvider(events, snapshots, checkpoints)

This is how to test a caching service's behaviour when another instance writes the same stream.

Change subscription timing

val backend = InMemoryProvider( subscriptionConfig = InMemorySubscriptionConfig( pollInterval = 1.milliseconds, options = SubscriptionOptions(maxBatchSize = 10), ))

A small maxBatchSize is useful for testing how a subscriber behaves across batch boundaries.

Seed with the published test fixtures

akashic-core publishes its test fixtures as a feature variant. Add them to the test classpath:

dependencies { testImplementation(testFixtures("codes.laurence.akashic:akashic-core:0.0.5")) }

prepareAppendFixture prepares an append exactly as the service does, for seeding a store with history or for standing in for an append whose outcome was unknown. committed wraps any event as a CommittedEvent, for driving a subscriber with events no store wrote. Neither needs an opt-in: the fixtures carry the internal preparer's opt-in themselves.

class SeededStoreTest { private val backend = InMemoryProvider() private val accounts = backend.aggregateService(AccountDefinition) @Test fun `a seeded stream loads like one the service wrote`() { runBlocking { val store = backend.aggregateStore(AccountDefinition) store.append( prepareAppendFixture( eventTypes = AccountDefinition.eventTypes, codec = AccountDefinition.eventCodec, aggregateId = "acc-1", expectedVersion = null, commandId = CommandId("seed-acc-1"), occurredAt = Clock.System.now(), events = listOf(AccountEvent.Opened("Ada"), AccountEvent.Deposited(100, null)), )) val found = accounts.getById("acc-1") as AggregateLookupResult.Found assertThat(found.committedState.version).isEqualTo(1) assertThat(found.committedState.state.balance).isEqualTo(100) } } @Test fun `a committed event drives a subscriber without a store`() { runBlocking { accounts.handle(AccountCommand.Open("Grace").forAccount("acc-2")) val processor = TransferProcessor<CheckpointLong>(accounts) { "checkpoint:${it?.id ?: "beginning"}" } val sent = AccountEvent.TransferSent("acc-2", 40) .committed( aggregateId = "acc-1", version = 2, aggregateType = AccountDefinition.aggregateType, ) processor.onEvents( SubscriptionBatch( events = listOf(SubscriptionEvent(CheckpointLong(2), sent)), precedingCheckpoint = CheckpointLong(1), )) val receiver = accounts.getById("acc-2") as AggregateLookupResult.Found assertThat(receiver.committedState.state.balance).isEqualTo(40) } } }

What still needs a real backend

The in-memory backend proves your domain, codecs and subscribers. Keep a few tests against the real database for what it cannot show: migrations, connection handling, and lease behaviour across instances.

14 November 2026