Skip to content

Cratis Chronicle append collection for integration tests

Cratis Chronicle’s IEventAppendCollection captures event-log append outcomes from the client under test, so you can assert on both the events your operation produces and their results. Use it with the .NET integration fixtures when a test needs a running kernel. It does not observe appends made by another client or process, even against the same event store.

Call StartCollectingAppends() on the fixture before the operation you want to test. The collector subscribes to the event log’s AppendOperations notifications and keeps each event and its append result together as an AppendedEventWithResult. Direct calls to EventStore.EventLog.Append and EventStore.EventLog.AppendMany use this path. So do reactors that call ICommandPipeline.Execute(), because the command pipeline commits its unit of work through AppendMany on the same client.

The collection includes rejected appends as well as successful ones. An idempotent retry that returns an already-appended result does not emit a new append notification, so it does not add another entry.

For a direct Append, the entry is available when the awaited call returns. A reactor’s follow-up append can arrive later: use WaitForCount() before asserting on that event. Waiting for a count confirms that append outcomes arrived; it does not by itself confirm other observer work.

Add the Cratis.Chronicle.XUnit.Integration package for IEventAppendCollection and ChronicleInProcessFixture. The in-process fixture runs the kernel in the test process and MongoDB through Testcontainers, so this setup needs a container runtime.

Define an xUnit collection to share the fixture among test classes marked with that collection. The project-local Specification base below binds Specification<TChronicleFixture> to ChronicleInProcessFixture, so each context can use the same base. Its AutoDiscoverArtifacts = false setting means the examples nominate their event types and reactors explicitly:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
// One-time test project setup: a collection definition sharing one ChronicleInProcessFixture
// across test classes, and a project-local Specification convenience base.
[CollectionDefinition(Name)]
public class ChronicleCollection : ICollectionFixture<ChronicleInProcessFixture>
{
public const string Name = "Chronicle";
}
public class Specification(ChronicleInProcessFixture fixture) : Specification<ChronicleInProcessFixture>(fixture)
{
public override bool AutoDiscoverArtifacts => false;
}
[EventType]
public record ItemRegistered(string Name);
namespace given
{
public class an_event_append_collection_scope(ChronicleInProcessFixture fixture) : Specification(fixture)
{
public EventSourceId EventSourceId = null!;
public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(ItemRegistered)];
void Establish() => EventSourceId = EventSourceId.New();
async Task Because()
{
AppendedEventsCollector = StartCollectingAppends();
await EventStore.EventLog.Append(EventSourceId, new ItemRegistered("Widget"));
}
void Destroy() => AppendedEventsCollector?.Dispose();
}
}
}

View C# snippet source on GitHub

The ChronicleCollection.Name used by the later test classes refers to this collection definition. Keep the definition and convenience base in your test project; the remaining examples build on them.

Start collecting in Because(), immediately before the operation under test. That keeps setup events out of the assertions. Store the collector on the given context so the facts can inspect it, then dispose it in Destroy():

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
// One-time test project setup: a collection definition sharing one ChronicleInProcessFixture
// across test classes, and a project-local Specification convenience base.
[CollectionDefinition(Name)]
public class ChronicleCollection : ICollectionFixture<ChronicleInProcessFixture>
{
public const string Name = "Chronicle";
}
public class Specification(ChronicleInProcessFixture fixture) : Specification<ChronicleInProcessFixture>(fixture)
{
public override bool AutoDiscoverArtifacts => false;
}
[EventType]
public record ItemRegistered(string Name);
namespace given
{
public class an_event_append_collection_scope(ChronicleInProcessFixture fixture) : Specification(fixture)
{
public EventSourceId EventSourceId = null!;
public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(ItemRegistered)];
void Establish() => EventSourceId = EventSourceId.New();
async Task Because()
{
AppendedEventsCollector = StartCollectingAppends();
await EventStore.EventLog.Append(EventSourceId, new ItemRegistered("Widget"));
}
void Destroy() => AppendedEventsCollector?.Dispose();
}
}
}

View C# snippet source on GitHub

Disposal unsubscribes the collector, so later appends no longer accumulate in it. While a scope is active, it captures notifications from the subscribed event log, not only events for one event source. Filter by event type or context when other activity on that client could be present.

Each entry in All pairs the event passed to the append with the operation’s outcome. Check Result before treating the event as successfully stored:

Member Type Description
Event AppendedEvent The event submitted for append, including its context and content
Event.Content object The event object supplied to the append (cast to your event type for assertions)
Event.Context EventContext Metadata: event source, sequence number, correlation ID, causation chain, etc.
Event.Context.EventSourceId EventSourceId The event source the event was appended for
Event.Context.SequenceNumber EventSequenceNumber Assigned position, or unavailable for a failed append
Event.Context.CorrelationId CorrelationId The append’s correlation ID
Event.Context.Causation IEnumerable<Causation> The causation chain active at the time of the append
Result AppendResult The outcome of the append operation
Result.IsSuccess bool true when there are no constraint violations, concurrency violations, or errors
Result.SequenceNumber EventSequenceNumber Assigned sequence number; EventSequenceNumber.Unavailable when the append failed
Result.HasConstraintViolations bool true when at least one constraint violation was returned
Result.HasConcurrencyViolations bool true when at least one concurrency violation was returned
Result.HasErrors bool true when at least one error was returned
Result.ConstraintViolations IEnumerable<ConstraintViolation> Constraint violations, if any
Result.ConcurrencyViolation ConcurrencyViolation? Concurrency violation, if any
Result.Errors IEnumerable<AppendError> Errors, if any

IEventAppendCollection exposes three members:

Member Description
All A snapshot of every AppendedEventWithResult captured so far
Last The most recently captured AppendedEventWithResult; throws when nothing has been collected
WaitForCount(count, timeout?) Waits asynchronously until at least count events have been collected

The setup context appends ItemRegistered after starting the collector. A spec derived from Given<TSetup> can inspect it through Context. These facts check that one entry arrived with the expected event type and a successful result:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
[Collection(ChronicleCollection.Name)]
public class and_collecting_the_registered_item(given.an_event_append_collection_scope context)
: Given<given.an_event_append_collection_scope>(context)
{
[Fact] void should_collect_one_event() => Context.AppendedEventsCollector.All.Count.ShouldEqual(1);
[Fact] void should_have_appended_the_event() => Context.AppendedEventsCollector.All[0].Event.Content.ShouldBeOfExactType<ItemRegistered>();
[Fact] void should_be_successful() => Context.AppendedEventsCollector.All[0].Result.IsSuccess.ShouldBeTrue();
[Fact] void should_have_a_valid_sequence_number() => Context.AppendedEventsCollector.All[0].Result.SequenceNumber.IsActualValue.ShouldBeTrue();
}
}

View C# snippet source on GitHub

When an operation produces several events, select the one your assertion concerns. This example finds SecondItemAdded by type and checks its name instead of relying on its position in the collection:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
[EventType]
public record FirstItemAdded(string Name);
[EventType]
public record SecondItemAdded(string Name);
namespace given
{
public class a_multiple_events_scope(ChronicleInProcessFixture fixture) : Specification(fixture)
{
public EventSourceId EventSourceId = null!;
public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(FirstItemAdded), typeof(SecondItemAdded)];
void Establish() => EventSourceId = EventSourceId.New();
async Task Because()
{
AppendedEventsCollector = StartCollectingAppends();
await EventStore.EventLog.Append(EventSourceId, new FirstItemAdded("Widget"));
await EventStore.EventLog.Append(EventSourceId, new SecondItemAdded("Gadget"));
}
void Destroy() => AppendedEventsCollector?.Dispose();
}
}
[Collection(ChronicleCollection.Name)]
public class and_locating_the_second_event(given.a_multiple_events_scope context)
: Given<given.a_multiple_events_scope>(context)
{
AppendedEventWithResult SecondEvent => Context.AppendedEventsCollector.All.First(e => e.Event.Content is SecondItemAdded);
[Fact] void should_locate_the_second_event() => SecondEvent.Event.Content.ShouldBeOfExactType<SecondItemAdded>();
[Fact] void should_carry_the_correct_name() => ((SecondItemAdded)SecondEvent.Event.Content).Name.ShouldEqual("Gadget");
}
}

View C# snippet source on GitHub

To prove that placing an order schedules a shipment, collect both the original OrderPlaced event and the reactor’s ShipmentScheduled follow-up. The test waits for the reactor to become active before appending the order, then waits for two collected entries before asserting on the shipment.

The reactor appends a shipment event for the same event source as the order:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
[EventType]
public record OrderPlaced(string OrderId);
[EventType]
public record ShipmentScheduled(string OrderId);
public class ShipmentReactor(IEventLog eventLog) : IReactor
{
public Task OnOrderPlaced(OrderPlaced evt, EventContext ctx) =>
eventLog.Append(ctx.EventSourceId, new ShipmentScheduled(evt.OrderId));
}
}

View C# snippet source on GitHub

The context nominates both event types and the reactor, then registers the reactor’s service:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
namespace given
{
public class a_shipment_reactor_context(ChronicleInProcessFixture fixture) : Specification(fixture)
{
public EventSourceId EventSourceId = null!;
public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(OrderPlaced), typeof(ShipmentScheduled)];
public override IEnumerable<Type> Reactors => [typeof(ShipmentReactor)];
protected override void ConfigureServices(IServiceCollection services) =>
services.AddSingleton<ShipmentReactor>();
void Establish() => EventSourceId = EventSourceId.New();
void Destroy() => AppendedEventsCollector?.Dispose();
}
}
}

View C# snippet source on GitHub

The spec starts collecting only after the reactor is active:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
[Collection(ChronicleCollection.Name)]
public class and_collecting_the_scheduled_shipment(and_collecting_the_scheduled_shipment.context context)
: Given<and_collecting_the_scheduled_shipment.context>(context)
{
#pragma warning disable CS8981 // "context" is a conventional, lowercase BDD nested-class name
public class context(ChronicleInProcessFixture fixture) : given.a_shipment_reactor_context(fixture)
{
async Task Because()
{
var reactor = EventStore.Reactors.GetHandlerFor<ShipmentReactor>();
await reactor.WaitTillActive();
AppendedEventsCollector = StartCollectingAppends();
await EventStore.EventLog.Append(EventSourceId, new OrderPlaced("order-123"));
// Wait for the reactor's follow-up append to arrive
await AppendedEventsCollector.WaitForCount(2);
}
}
#pragma warning restore CS8981
AppendedEventWithResult Shipment => Context.AppendedEventsCollector.All
.First(e => e.Event.Content is ShipmentScheduled);
[Fact] void should_schedule_a_shipment() =>
Shipment.Event.Content.ShouldBeOfExactType<ShipmentScheduled>();
[Fact] void should_carry_the_order_id() =>
((ShipmentScheduled)Shipment.Event.Content).OrderId.ShouldEqual("order-123");
[Fact] void should_be_successful() =>
Shipment.Result.IsSuccess.ShouldBeTrue();
[Fact] void should_have_a_valid_sequence_number() =>
Shipment.Result.SequenceNumber.IsActualValue.ShouldBeTrue();
}
}

View C# snippet source on GitHub

WaitForCount accepts an optional TimeSpan timeout (default: 5 seconds) and throws TimeoutException if the expected count is not reached in time. WaitTillActive() ensures the reactor is registered and listening on the server before the test appends the triggering event.

The 5-second default also applies to the WaitTillActive helpers. Set the CHRONICLE_TEST_TIMEOUT_SECONDS environment variable to a positive number of seconds to change it, for example on slow CI machines. While a debugger is attached the default wait is infinite.

A collected event does not necessarily mean an event was stored. When a reactor’s direct append is rejected by a constraint, the collector records the violation in AppendedEventWithResult.Result. The append returns that result instead of throwing.

Here, UniqueValueReactor directly appends UniqueValueFollowUp without ICommandPipeline. A constraint requires the follow-up’s value to be unique:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
[EventType]
public record UniqueValueRecorded(string UniqueValue);
[EventType]
public record UniqueValueFollowUp(string UniqueValue);
public class UniqueValueFollowUpConstraint : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(b => b.On<UniqueValueFollowUp>(e => e.UniqueValue));
}
public class UniqueValueReactor(IEventLog eventLog) : IReactor
{
public Task OnUniqueValueRecorded(UniqueValueRecorded evt, EventContext ctx) =>
eventLog.Append(ctx.EventSourceId, new UniqueValueFollowUp(evt.UniqueValue));
}
}

View C# snippet source on GitHub

The shared given context:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
namespace given
{
public class a_unique_value_reactor_context(ChronicleInProcessFixture fixture) : Specification(fixture)
{
public IEventAppendCollection AppendedEventsCollector = null!;
public override IEnumerable<Type> EventTypes => [typeof(UniqueValueRecorded), typeof(UniqueValueFollowUp)];
public override IEnumerable<Type> ConstraintTypes => [typeof(UniqueValueFollowUpConstraint)];
public override IEnumerable<Type> Reactors => [typeof(UniqueValueReactor)];
protected override void ConfigureServices(IServiceCollection services) =>
services.AddSingleton<UniqueValueReactor>();
void Destroy() => AppendedEventsCollector?.Dispose();
}
}
}

View C# snippet source on GitHub

The spec appends the same unique value from two event sources. It waits for four entries: two input appends and two follow-up attempts. One follow-up succeeds; the duplicate violates the constraint. The assertion selects the rejected result, where HasConstraintViolations is true and IsSuccess is false, and checks which event was refused:

namespace Cratis.Chronicle.Docs.EventAppendCollection
{
[Collection(ChronicleCollection.Name)]
public class and_a_reactor_directly_appends_a_duplicate_unique_value(and_a_reactor_directly_appends_a_duplicate_unique_value.context context)
: Given<and_a_reactor_directly_appends_a_duplicate_unique_value.context>(context)
{
#pragma warning disable CS8981 // "context" is a conventional, lowercase BDD nested-class name
public class context(ChronicleInProcessFixture fixture) : given.a_unique_value_reactor_context(fixture)
{
public string UniqueValue = null!;
async Task Because()
{
var reactor = EventStore.Reactors.GetHandlerFor<UniqueValueReactor>();
await reactor.WaitTillActive();
UniqueValue = Guid.NewGuid().ToString();
var firstEventSourceId = EventSourceId.New();
var secondEventSourceId = EventSourceId.New();
AppendedEventsCollector = StartCollectingAppends();
await EventStore.EventLog.Append(firstEventSourceId, new UniqueValueRecorded(UniqueValue));
await EventStore.EventLog.Append(secondEventSourceId, new UniqueValueRecorded(UniqueValue));
await AppendedEventsCollector.WaitForCount(4);
}
}
#pragma warning restore CS8981
AppendedEventWithResult ViolatingAppend => Context.AppendedEventsCollector.All
.First(e => e.Result.HasConstraintViolations);
[Fact] void should_have_a_constraint_violation() =>
ViolatingAppend.Result.HasConstraintViolations.ShouldBeTrue();
[Fact] void should_not_be_successful() =>
ViolatingAppend.Result.IsSuccess.ShouldBeFalse();
[Fact] void should_have_attempted_the_follow_up_event() =>
ViolatingAppend.Event.Content.ShouldBeOfExactType<UniqueValueFollowUp>();
}
}

View C# snippet source on GitHub

Use the shipment example with the test project setup to check a reactor against the running kernel. If you only need to specify the reactor’s handling logic, use ReactorScenario to test that behavior in process without containers.