Cratis Chronicle testing boundaries and setup
Cratis Chronicle’s testing helpers let you check event appends and read model state without starting a separate kernel. Start with the in-process scenario your client supports, then use an integration test against a running kernel for behavior that depends on a connection, delivery to observers (event consumers), or persistent storage. In .NET, Cratis.Chronicle.XUnit.Integration provides that integration boundary with a running kernel and MongoDB through Testcontainers.
In .NET, use Cratis Specifications to separate setup, the operation under test, and its expected outcome. Seed existing events in Establish() or a scenario’s Given builder. Run the operation in Because(), then use each [Fact] to check an appended event, read model value, or side effect.
Choosing the right test boundary
Section titled “Choosing the right test boundary”Choose the boundary from the question the spec needs to answer. A read model calculation does not need a database, but checking that its sink, the component that stores the model, wrote a document does. These are the .NET starting points:
| What to prove | Start with | What it does not prove |
|---|---|---|
| Event appends, constraint violations, sequencing | EventScenario |
Network serialization, kernel connection, persistent storage writes |
| Read model projection or reducer logic | ReadModelScenario<T> |
Sink writes, MongoDB queries, change stream subscription |
| Reactor side effects and event ordering | ReactorScenario<T> |
Network observer registration, kernel event dispatch, automatic redelivery |
| Actual storage writes, kernel connectivity, change streams | ChronicleInProcessFixture / ChronicleOutOfProcessFixture |
Isolation from other tests that share the same fixture host |
For .NET given/run/then specs, Cratis.Chronicle.Testing.Slices provides thin, single-run adapters: ProjectionSlice and keyed partial/exact read-model assertions, and ReactionSlice with ordered or any-order produced-event assertions. They reuse the scenario engines and do not add persistence, kernel delivery, or proof that a recorded side effect executed.
ReactorScenario<T> delivers each supplied event once. To check idempotence, meaning that handling the same event again does not repeat an unwanted side effect, write a spec that supplies the event twice.
The .NET integration fixtures available in Cratis.Chronicle.XUnit.Integration are:
ChronicleInProcessFixture: runs the kernel in the test process and MongoDB through Testcontainers.ChronicleOutOfProcessFixture: runs the kernel in a separate container, also using Testcontainers.ChronicleClientFixture: provides the client-side base for integration tests.ChronicleOrleansFixture: hosts an Orleans-based kernel for testing Chronicle’s own internals.
Only the in-process and out-of-process fixtures are documented here; the others are for framework or advanced scenarios.
Switching off an integration tier
Section titled “Switching off an integration tier”Skipping every fact does not necessarily stop xUnit from initializing the context fixture. Override ShouldBootstrap on your ChronicleClientFixture<TChronicleFixture> or either Specification variant with your tier predicate, for example protected override bool ShouldBootstrap => TierIsEnabled;. Keep the predicate stable for the context’s lifetime. It defaults to true; returning false skips context-owned bootstrap, storage/grain/client reset, scenario initialization and matching cleanup. A no-op OnInitializeAsync alone does not stop the earlier bootstrap and reset.
This gate does not stop construction of a backing fixture supplied by xUnit. ChronicleFixture starts its container eagerly: ChronicleInProcessFixture starts MongoDB, and ChronicleOutOfProcessFixture starts the Chronicle development container. A disabled tier must not register or construct that backing fixture if it needs to avoid containers. Exclude the backing fixture registration or keep the tier out of the run; overriding the context gate alone cannot make an eagerly constructed collection fixture container-free. See Switching off an xUnit integration tier for the lifecycle boundary.
.NET packages
Section titled “.NET packages”<PackageReference Include="Cratis.Specifications.XUnit" /><PackageReference Include="Cratis.Chronicle.Testing" />Use these references for Chronicle-only specs. Cratis.Chronicle.Testing brings in Cratis.Arc and Cratis.Arc.Core, including the ASP.NET Core shared framework, so you do not need separate Arc references unless you are overriding their versions.
Application hosts that reference Testing
Section titled “Application hosts that reference Testing”If your application host references Cratis.Chronicle.Testing, register the Chronicle client as usual. Testing keeps kernel commands and queries out of the application’s Arc endpoints without changing application commands, queries, or authorization policies. Registration order between Arc and Chronicle does not matter.
A dependency-injection container that also hosts the kernel keeps its kernel commands and queries. The kernel still needs them to dispatch its own work through Arc. This includes the in-process silo used by the xUnit fixtures. Chronicle identifies that host through the kernel’s administrator authorization policy, regardless of registration order.
For custom Arc providers, register individual ICommandHandlerProvider and IQueryPerformerProvider implementations. Do not replace the IInstancesOf<ICommandHandlerProvider> or IInstancesOf<IQueryPerformerProvider> collections. Testing rejects a replacement during client registration if it is already present, or at host startup if added afterward. The error explains how to register individual providers instead.
To add services during Chronicle client registration, implement IChronicleClientServices with a public parameterless constructor. Chronicle discovers it through the type universe and calls it for both web and non-web clients. Make its registrations safe to repeat: a host can register the client more than once. These hooks apply to the client container, not the isolated kernel pipeline.
Matching versions
Section titled “Matching versions”Match Cratis.Chronicle.Testing to your Chronicle client release. Chronicle and Arc have independent release numbers, so check that Testing release’s NuGet dependencies for its Arc requirements rather than matching the numbers. If you use the Cratis meta-package, check its dependencies too.
If you need to override the Arc dependency with a compatible newer release, pin both Cratis.Arc and Cratis.Arc.Core to the same version in Directory.Packages.props and reference them directly in the test project. Alternatively, enable CentralPackageTransitivePinningEnabled there so the central pins apply to transitive dependencies. Align any other Arc runtime packages with that version, do not go below Testing’s declared dependencies, and verify your scenarios after an override.
Use Cratis.Testing instead of Cratis.Chronicle.Testing when the same spec also tests Arc commands.
Application command execution scopes, including Chronicle transactions, wrap the application command in the outer Arc pipeline. The scenario’s internal append pipeline excludes your application’s ICommandExecutionScope implementations; they do not run again for each append. You therefore do not need to register their dependencies with the scenario harness.
Explicit artifacts and lifetime
Section titled “Explicit artifacts and lifetime”Artifacts are the event types, reducers, reactors, constraints, and migrations that a scenario needs to find. To choose them for one .NET run, pass Defaults configured with ChronicleOptions.ExplicitArtifacts. Those registrations feed scenario processing, not just discovery. A plain ReactorScenario<T> requires explicit reactor nomination; it does not discover an arbitrary class by its method signatures.
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.Testing;using Cratis.Chronicle.Testing.EventSequences;using Cratis.Chronicle.Testing.ReadModels;using Cratis.Chronicle.Testing.Reactors;using Cratis.Specifications;
namespace ExplicitScenarioExample{ public record Credited(int Amount); public record CreditNoted(int Amount); public record Balance(int Amount);
public class BalanceReducer { public Balance Reduce(Credited @event, Balance? current) => new((current?.Amount ?? 0) + @event.Amount); }
public class Notifier { public CreditNoted On(Credited @event) => new(@event.Amount); }
public static class Scenarios { public static async Task Verify() { var options = new ChronicleOptions(); options.ExplicitArtifacts.RegisterEventType<Credited>().RegisterEventType<CreditNoted>() .RegisterReducer<BalanceReducer>().RegisterReactor<Notifier>(); var defaults = new Defaults(new InMemoryClientArtifactsProvider(), null, options); var source = EventSourceId.New();
var readModel = new ReadModelScenario<Balance>(null, defaults); await readModel.Given.ForEventSource(source).Events(new Credited(3), new Credited(4)); readModel.Instance!.Amount.ShouldEqual(7);
using var reactor = new ReactorScenario<Notifier>(defaults); await reactor.Given.ForEventSource(source).Events(new Credited(3)); reactor.ShouldHaveProduced<CreditNoted>(_ => _.Amount == 3);
using var events = new EventScenario(defaults); (await events.EventLog.Append(source, new Credited(5))).ShouldBeSuccessful(); } }}Create separate defaults and options for independent runs. Each scenario store captures its artifact registrations when created; changing shared options later does not change that store. Do not mutate Defaults.Instance or the default artifact provider to configure one run.
For xUnit integration tests, configure explicit artifacts before creating the fixture host, client, or store. The registrations live as long as the host: reusing it keeps the first snapshot, even after rediscovery. Derived fixtures in the same closed ChronicleClientFixture<TChronicleFixture> family share that host; separate hosts capture independent snapshots.
A fixture that overrides ChronicleFixture.UsesPerContextMongoDBHost to return true creates a fresh host for each test context. Each context then captures its own artifact snapshot.
Use AutoDiscoverArtifacts = false to disable assembly discovery while keeping explicit nominations and automatic client registration. AutoDiscoverAndRegister = false is different: it requires you to discover and register manually.
See the .NET explicit registration reference for peer conflicts, migration binding and custom-provider limits.
.NET testing store identity
Section titled “.NET testing store identity”If your code distinguishes event stores or namespaces, give the test store the identity it expects. Construct EventStoreForTesting(serviceProvider, artifacts, options, time, eventStore, @namespace, capabilities: null) or Defaults(artifacts, serviceProvider, options, time, eventStore, @namespace).
Pass an EventStoreName for eventStore and an EventStoreNamespaceName for @namespace. EventStoreForTesting requires a ScenarioTime clock; Defaults accepts a null clock.
The resulting store uses that identity for its Name, Namespace, event log, and unit-of-work operations. Pass the defaults to ReadModelScenario, ReactorScenario or OccurrenceScenario to use the same identity there. If you supply an explicit store to a reactor scenario, it uses that store’s identity, including in delivered event contexts.
EventScenario has separate identity parameters; it does not inherit the defaults’ store identity. See EventScenario for its constructors.
Each store instance has isolated in-memory storage, even when identities match. Existing EventStoreForTesting and Defaults overloads still create their store as testing in namespace default.
Topics
Section titled “Topics”| Guide | Description |
|---|---|
| Events | Test event appends and constraint behavior in-process using EventScenario |
| Read Models | Test projections and reducers in-process using ReadModelScenario<TReadModel> |
| Reactors | Test reactor side-effects in-process using ReactorScenario<TReactor> |
| Occurrences and receipts | Drive leased trigger deliveries, retry time and commit-then-drop-reply recovery |
| Event append collection | Capture this client’s event-log append outcomes with IEventAppendCollection in an integration test |
A specification-shaped example
Section titled “A specification-shaped example”using Cratis.Chronicle.Events;using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.Testing.ReadModels;using Cratis.Specifications;using Xunit;
[EventType]public record AuthorRegistered(string Name);
[FromEvent<AuthorRegistered>]public record Author([Key] Guid Id, string Name);
public class when_projecting_a_registered_author : Specification{ readonly EventSourceId _authorId = EventSourceId.New(); readonly ReadModelScenario<Author> _scenario = new();
Task Because() => _scenario.Given .ForEventSource(_authorId) .Events(new AuthorRegistered("Jane Austen"));
[Fact] void should_set_the_author_name() => _scenario.Instance!.Name.ShouldEqual("Jane Austen");}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reducerimport io.cratis.chronicle.readModels.ReadModelimport io.cratis.chronicle.testing.ReadModelScenarioimport kotlinx.coroutines.runBlockingimport org.junit.jupiter.api.Assertions.assertEqualsimport org.junit.jupiter.api.Test
@EventTypedata class AuthorRegistered(val name: String)
@ReadModeldata class Author(val name: String = "")
@Reducerclass AuthorReducer { fun registered(event: AuthorRegistered) = Author(event.name)}
class WhenProjectingARegisteredAuthorTests {
@Test fun `the author read model carries the registered name`() = runBlocking { val scenario = ReadModelScenario<Author>(AuthorReducer())
val author = scenario.fold("author-1", AuthorRegistered("Jane Austen"))
assertEquals("Jane Austen", author!!.name) }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reducer;import io.cratis.chronicle.readModels.ReadModel;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TestingExampleSpec {
@EventType record AuthorRegistered(String name) { }
@ReadModel record Author(String name) { }
@Reducer static class AuthorReducer { Author registered(AuthorRegistered event) { return new Author(event.name()); } }
@Test void theAuthorReadModelCarriesTheRegisteredName() { var reducer = new AuthorReducer();
var author = reducer.registered(new AuthorRegistered("Jane Austen"));
assertEquals("Jane Austen", author.name()); }}defmodule MyApp.Events.TestingIndexAuthorRegistered do use Cratis.Chronicle.Events.EventType, id: "testing-index-author-registered"
defstruct [:name]end
defmodule MyApp.ReadModels.TestingIndexAuthor do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.TestingIndexAuthorRegistered
defstruct id: nil, name: nil
from TestingIndexAuthorRegistered, set: [id: :event_source_id, name: :name]end
defmodule MyApp.TestingIndexExampleSpecTest do use ExUnit.Case, async: true
alias MyApp.Events.TestingIndexAuthorRegistered alias MyApp.ReadModels.TestingIndexAuthor
test "projecting a registered author sets the author name" do author_id = "author-#{System.unique_integer([:positive])}"
{:ok, author} = Cratis.Chronicle.Testing.Projections.apply_event( TestingIndexAuthor, nil, %TestingIndexAuthorRegistered{name: "Jane Austen"}, author_id )
assert author.name == "Jane Austen" endendimport { field } from '@cratis/fundamentals';import { eventType, fromEvent } from '@cratis/chronicle';import { ReadModelScenario } from '@cratis/chronicle/testing';
@eventType()class AuthorRegistered { @field(String) name: string; constructor(name: string) { this.name = name; }}
@fromEvent(AuthorRegistered)class Author { @field(String) id = ''; @field(String) name = '';}
const authorScenario = new ReadModelScenario(Author);authorScenario.given.forEventSource('author-1').events(new AuthorRegistered('Jane Austen'));const projectedAuthor = await authorScenario.instance;if (projectedAuthor?.name !== 'Jane Austen') throw new Error('Expected the registered author name');This spec asks whether the Author read model contains the name the screen needs after AuthorRegistered. The projection or reducer runs in process, depending on the client. No database is needed to check that calculation.
What the harness stands in for
Section titled “What the harness stands in for”The .NET helpers use Chronicle’s projection and reducer engines, constraint evaluation, and reactor dispatch with its in-memory storage. By default, each scenario owns a store shared by its event log, named sequences, and in-process services. They bypass gRPC and the observer lifecycle, so a passing scenario does not establish network delivery or persistent storage behavior.
Use the integration fixtures to check MongoDB sink writes, observer registration, or change stream checkpoints against a running kernel. In those tests, IEventAppendCollection records the client’s append outcomes; it does not replace assertions on stored documents or observer state. Follow Event append collection to set up a fixture and wait for a reactor’s follow-up append.
Continue with Test a slice to combine these boundaries in a slice, or Testing with Cratis for the testing model across Specifications, Arc, and full stack slices.