Cratis Chronicle: test a vertical slice
Test a Cratis Chronicle slice by checking the events its command appends and the read model those events produce. A slice is one path through a feature, from an action to its resulting state. In-process scenarios let you check those two parts without starting a Chronicle server or database.
Real engines, in-memory storage
Section titled “Real engines, in-memory storage”The C# examples use Cratis.Chronicle.Testing. EventScenario runs the kernel append path with in-memory storage, including serialization and constraint validation. ReadModelScenario<TReadModel> runs the projection or reducer engine against supplied events. These are separate checks: appending through EventScenario does not start observers or update a read model for you.
The read-model harness also substitutes infrastructure such as projection storage and compliance services. It is not a running kernel with only its database replaced.
dotnet add package Cratis.Chronicle.TestingThe examples below use the Cratis Specifications style (Establish/Because/should_), but the scenarios work with any test framework.
Test the events with EventScenario
Section titled “Test the events with EventScenario”Create an EventScenario, seed any pre-existing history with Given, and append through its EventLog. Assert on the AppendResult so the test checks whether the append was accepted, not just whether the call completed:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Testing.EventSequences;using Cratis.Specifications;using Xunit;
public record TestSliceBookId(Guid Value) : EventSourceId<Guid>(Value){ public static TestSliceBookId New() => new(Guid.NewGuid());}
[EventType]public record TestSliceBookAdded(string Title, [property: Unique(name: "TestSliceUniqueIsbn")] string Isbn);
[EventType]public record TestSliceBookBorrowed(string BorrowedBy);
public class when_adding_a_book : Specification, IDisposable{ EventScenario _scenario = null!; AppendResult _result = null!;
void Establish() => _scenario = new EventScenario();
async Task Because() => _result = await _scenario.EventLog.Append( TestSliceBookId.New(), new TestSliceBookAdded("The Pragmatic Programmer", "978-0135957059"));
[Fact] void should_be_successful() => _result.ShouldBeSuccessful();
public void Dispose() => _scenario.Dispose();}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestSliceAppendBookAdded do use Cratis.Chronicle.Events.EventType, id: "test-slice-append-book-added"
defstruct [:title, :isbn]end
defmodule MyApp.TestSliceAppendTest do # Runs against an in-memory kernel, so it needs no Chronicle server. use Cratis.Chronicle.Testing.Case, event_types: [MyApp.Events.TestSliceAppendBookAdded]
import Cratis.Chronicle.Testing.Assertions
alias Cratis.Chronicle.EventSequences.EventLog alias MyApp.Events.TestSliceAppendBookAdded
test "adding a book appends a BookAdded event", %{chronicle: client} do book_id = "book-#{System.unique_integer([:positive])}"
result = EventLog.append( book_id, %TestSliceAppendBookAdded{title: "The Pragmatic Programmer", isbn: "978-0135957059"}, client: client )
assert result == :ok
assert_appended(client, TestSliceAppendBookAdded, event_source_id: book_id) endendTypeScript does not support this workflow yet.To test command behavior, pass the scenario’s EventLog to the command code under test. The direct append above checks the append path; it does not invoke your command for you.
Constraints are discovered from the configured client artifacts. With a unique-ISBN constraint such as the one in Enforce a unique value, seed a book and then append a duplicate. The expected result is a constraint violation:
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Testing.EventSequences;using Cratis.Specifications;using Xunit;
public class and_the_isbn_already_exists : Specification, IDisposable{ EventScenario _scenario = null!; AppendResult _result = null!;
async Task Establish() { _scenario = new EventScenario(); await _scenario.Given .ForEventSource(TestSliceBookId.New()) .Events(new TestSliceBookAdded("The Pragmatic Programmer", "978-0135957059")); }
async Task Because() => _result = await _scenario.EventLog.Append( TestSliceBookId.New(), new TestSliceBookAdded("The Pragmatic Programmer, 2nd ed.", "978-0135957059"));
[Fact] void should_be_rejected() => _result.ShouldBeFailed(); [Fact] void should_report_the_violated_constraint() => _result.ShouldHaveConstraintViolationFor("TestSliceUniqueIsbn");
public void Dispose() => _scenario.Dispose();}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestSliceConstraintBookAdded do use Cratis.Chronicle.Events.EventType, id: "test-slice-constraint-book-added"
defstruct [:title, :isbn]
unique(:isbn, name: "TestSliceConstraintUniqueIsbn")end
defmodule MyApp.TestSliceConstraintTest do # Runs against an in-memory kernel, which enforces unique constraints on append. use Cratis.Chronicle.Testing.Case, event_types: [MyApp.Events.TestSliceConstraintBookAdded]
import Cratis.Chronicle.Testing.Assertions
alias Cratis.Chronicle.EventSequences.EventLog alias MyApp.Events.TestSliceConstraintBookAdded
test "adding a second book with an isbn already in use is rejected", %{chronicle: client} do first = "book-#{System.unique_integer([:positive])}" second = "book-#{System.unique_integer([:positive])}"
:ok = EventLog.append( first, %TestSliceConstraintBookAdded{title: "The Pragmatic Programmer", isbn: "978-0135957059"}, client: client )
result = EventLog.append( second, %TestSliceConstraintBookAdded{ title: "The Pragmatic Programmer, 2nd ed.", isbn: "978-0135957059" }, client: client )
assert_constraint_violation(result, "TestSliceConstraintUniqueIsbn") refute_appended(client, TestSliceConstraintBookAdded, event_source_id: second) endendTypeScript does not support this workflow yet.Use ShouldBeSuccessful/ShouldBeFailed for the overall outcome and ShouldHaveConstraintViolationFor to identify the rejected rule. Append result assertions also covers concurrency violations and errors. Create a fresh EventScenario per spec and dispose it; calls on the same instance share its accumulated history.
Test the read model with ReadModelScenario
Section titled “Test the read model with ReadModelScenario”Use ReadModelScenario<TReadModel> to check how recorded facts become state. It detects whether a reducer, fluent projection or model-bound attributes build the model, then applies the supplied history through the corresponding engine:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.Testing.ReadModels;using Cratis.Specifications;using Xunit;
[FromEvent<TestSliceBookAdded>]public record TestSliceBook( [Key] Guid Id, string Title, [SetValue<TestSliceBookBorrowed>(true)] bool OnLoan, [SetFrom<TestSliceBookBorrowed>(nameof(TestSliceBookBorrowed.BorrowedBy))] string? BorrowedBy);
public class when_a_book_is_borrowed : Specification{ readonly TestSliceBookId _bookId = TestSliceBookId.New(); readonly ReadModelScenario<TestSliceBook> _scenario = new();
Task Because() => _scenario.Given .ForEventSource(_bookId) .Events( new TestSliceBookAdded("The Pragmatic Programmer", "978-0135957059"), new TestSliceBookBorrowed("Ada Lovelace"));
[Fact] void should_be_on_loan() => _scenario.Instance!.OnLoan.ShouldBeTrue(); [Fact] void should_record_the_borrower() => _scenario.Instance!.BorrowedBy.ShouldEqual("Ada Lovelace");}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.TestSliceReadModelBookAdded do use Cratis.Chronicle.Events.EventType, id: "test-slice-read-model-book-added"
defstruct [:title, :isbn]end
defmodule MyApp.Events.TestSliceReadModelBookBorrowed do use Cratis.Chronicle.Events.EventType, id: "test-slice-read-model-book-borrowed"
defstruct [:borrowed_by]end
defmodule MyApp.ReadModels.TestSliceReadModelBook do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{TestSliceReadModelBookAdded, TestSliceReadModelBookBorrowed}
defstruct id: nil, title: nil, borrowed_by: nil
from TestSliceReadModelBookAdded, set: [id: :event_source_id, title: :title]
from TestSliceReadModelBookBorrowed, set: [borrowed_by: :borrowed_by]end
defmodule MyApp.TestSliceReadModelTest do # Evaluates the read model's `from/2` declarations in memory, so it needs no Chronicle server. use ExUnit.Case, async: true
alias Cratis.Chronicle.Testing.Projections alias MyApp.Events.{TestSliceReadModelBookAdded, TestSliceReadModelBookBorrowed} alias MyApp.ReadModels.TestSliceReadModelBook
test "borrowing a book records who has it" do book_id = "book-#{System.unique_integer([:positive])}"
{:ok, book} = Projections.apply_event( TestSliceReadModelBook, nil, %TestSliceReadModelBookAdded{title: "The Pragmatic Programmer", isbn: "978-0135957059"}, book_id )
assert book.borrowed_by == nil
{:ok, book} = Projections.apply_event( TestSliceReadModelBook, book, %TestSliceReadModelBookBorrowed{borrowed_by: "Ada Lovelace"}, book_id )
assert book.borrowed_by == "Ada Lovelace" endendTypeScript does not support this workflow yet.Here Given supplies the events and Instance exposes the resulting model. The assertion checks that borrowing the book changes its availability. If it fails, inspect the supplied history, read model declaration and mapping, such as [SetFrom<T>]/[SetValue<T>] attributes or reducer logic. Using the real engine does not rule out a mistake in the test setup.
What this does and doesn’t cover
Section titled “What this does and doesn’t cover”Together these checks establish what the exercised code appends and how the supplied facts become state. They do not establish that a deployed observer catches up, that the network connection works, or that a production sink behaves as expected. Use integration tests with a real kernel for those boundaries.
They also do not exercise your HTTP surface or UI. Test those through your application framework rather than treating an append or projection assertion as proof of the whole feature.
See also
Section titled “See also”Continue with EventScenario or ReadModelScenario to configure initial state and dependencies. If the slice also reacts to events, Testing introduces ReactorScenario for checking those side effects.