We are going to design a domain event testing strategy that incorporates:
Snapshot fixtures: to capture the state of an event (or aggregate) at a point in time and compare against in tests.
Contract tests: to ensure that the events produced by the system adhere to a contract (schema, required fields, etc.) and can be consumed by other services.
Golden assertions: a pattern where we store the expected output (event) in a file (golden file) and compare the actual event structure to the golden file.
Steps:
Event Structure:
We assume events are immutable and have a well-defined structure (e.g., a class with fields).
We also assume we have a way to serialize/deserialize the event (e.g., to JSON).
Snapshot Fixtures:
For a given event, we can take a snapshot of its current state (maybe the entire event or a subset) and save it as a fixture.
In tests, we can compare the event under test to the snapshot.
This is useful when we want to ensure that the event structure does not change accidentally.
Contract Tests:
We can use a contract testing tool (like Pact) or define our own schema validation (using JSON Schema, for example).
We can have a set of test cases that validate the event against the contract (schema) and also check required fields, data types, etc.
Alternatively, we can generate the contract (schema) from the event class and then validate against it.
Golden Assertions:
We store the expected event (in a serialized form, e.g., JSON) in a file (golden file).
In the test, we generate the event, serialize it, and compare it to the golden file.
If the golden file is missing, we can generate it (with a flag) but that should be a conscious action.
Implementation Plan:
Let's assume we are using a language like Java, but the concepts are language-agnostic.
Steps for a test:
a) Create an event (by invoking the code that produces it).
b) Serialize the event to a canonical string (e.g., JSON with sorted keys, no whitespace).
c) Compare the serialized event to:
- The snapshot (if we are using snapshot testing) OR
- The golden file (if we are using golden assertions) OR
- Both (if we want to ensure the event structure and the exact output).
However, note that snapshot testing and golden assertions are similar. The difference is often in the workflow:
- Snapshot: automatically update the snapshot when the test fails and is approved (often done automatically in test frameworks like Jest).
- Golden: manually update the golden file when the change is intentional.
We can combine both: have a snapshot that is stored in a file and updated only when we run the test with a special flag (like --update-snapshots).
For contract tests, we can have a separate validation step that checks the event against a schema.
Proposed Test Structure:
For each event type:
Unit tests for event creation (if the event has business logic) - not the focus here.
Serialization tests: ensure that the event can be serialized and deserialized correctly.
Snapshot test:
Generate the event (with specific data) and serialize it.
Compare the serialized string with the stored snapshot (in a file).
If the snapshot doesn't exist, create it (or fail until we create it with a flag).
If the snapshot exists and doesn't match, fail the test (unless we are updating snapshots).
Contract test:
Validate the event against a JSON schema (or other contract definition).
We can have a schema per event type or a combined schema for all events.
Golden assertion (if different from snapshot): same as above but maybe for a more complex scenario where we want to store the entire event with multiple fields and nested structures.
However, note: snapshot and golden are essentially the same. We can unify them as "golden files" and call the test a "golden test".
Let's design:
We'll have a directory for golden files: src/test/resources/golden/events/
For each test method, we'll have a golden file named after the test method (or the event type and scenario).
Example:
Test method: testOrderCreatedEvent
Golden file: order_created_event.json
But note: we might want to test multiple scenarios for the same event type. So we can have:
We'll let the test method specify the path to the golden file.
Steps in the test:
Setup: create the event (or aggregate) and produce the event.
Serialize the event to a canonical JSON string (with sorted keys, and maybe without whitespace).
Read the golden file (if exists) and compare.
If the golden file doesn't exist, write the current serialized event to the golden file (only if a flag is set, otherwise fail).
If the golden file exists and the content doesn't match, fail the test.
For contract tests:
We can have a JSON schema for each event type. We can generate the schema from the event class (if possible) or write it by hand.
Steps:
Load the schema for the event type.
Validate the event (as an object) against the schema.
We can do this in the same test as the golden test, or separately.
Proposed:
We'll have two test methods for each event scenario:
code
- One for golden assertion (exact output).
- One for contract (schema validation).
But we can combine them in one test: first validate the contract, then compare the golden.
However, note: the golden file is an example of a valid event. So if the contract changes, we have to update the golden files.
So:
code
Step 1: Validate the event against the contract (schema). If it fails, then we don't even compare the golden.
Step 2: If the contract passes, then compare the event to the golden file.
But what if the contract changes? Then the golden file might become invalid. So we must update the contract and then update the golden files.
Alternatively, we can have the golden file be the source of truth for the contract? That's risky because the golden file is just one example.
Better:
code
- The contract (schema) is the source of truth for the structure.
- The golden file is an example of a valid event (with specific data) that we use for exact output comparison.
So:
code
We must maintain the schema and the golden files separately.
How to generate the schema?
code
We can have a tool that generates the JSON schema from the event class. Then we keep the generated schema in version control.
But note: if we change the event class, we must update the schema and the golden files.
Alternatively, we can generate the schema on the fly in the test and then validate the event against the generated schema? That would ensure that the event is always valid according to its own class.
However, the contract is not just about the structure of one event but also about the entire contract (maybe including multiple events). So we might have a separate contract definition.
Given the complexity, let's assume:
code
We have a JSON schema for each event type that is maintained separately (maybe in a `contracts` directory).
Then in the test:
code
- Load the schema for the event type.
- Validate the event (as a JSON object) against the schema.
And then we also compare the event (serialized) to the golden file.
But note: the golden file is an instance of the event that should be valid according to the schema.
So if the schema changes, we must update the golden files to be valid under the new schema.
Therefore, we can have:
code
Test for event `OrderCreated`:
1. Create an `OrderCreated` event with test data.
2. Serialize to JSON (canonical).
3. Validate against `OrderCreated` schema.
4. Compare the serialized JSON to the golden file.
If the schema changes, we:
code
1. Update the schema file.
2. Update the golden files (if necessary) to comply with the new schema.
How to update golden files?
code
We can run the tests with a flag (e.g., `-DupdateGoldenFiles=true`) that overwrites the golden file with the current event.
But note: the event in the test might have test data that is not representative of all valid events. So we must be cautious.
Alternatively, we can have multiple golden files for multiple scenarios.
Summary:
We'll design:
code
- A base test class for event testing that provides:
protected void assertEventMatchesGolden(Object event, String goldenFilePath) throws Exception {
// Serialize event to canonical JSON string.
// Read golden file (if exists) and compare.
// If golden file doesn't exist and updateGoldenFiles flag is set, write the current JSON to the golden file.
// If golden file exists and doesn't match, fail.
}
protected void assertEventConformsToContract(Object event, String schemaFilePath) throws Exception {
// Load the JSON schema from schemaFilePath.
// Validate the event (as a JSON object) against the schema.
}
- Then in each test for an event:
@Test
public void testOrderCreatedEvent() throws Exception {
OrderCreatedEvent event = createOrderCreatedEvent(); // with test data
String goldenFile = "events/order_created/when_order_is_placed.json";
String schemaFile = "contracts/order_created_schema.json";
assertEventConformsToContract(event, schemaFile);
assertEventMatchesGolden(event, goldenFile);
}
We can also have a test that generates the schema from the event class and then writes it to a file (if we are generating the schema). But that's a separate concern.
Considerations:
code
- How to handle non-deterministic fields (like timestamps, IDs)? We must ensure that the test data is fixed, or we must exclude those fields from the snapshot/golden.
Options:
1. In the test, set fixed values for non-deterministic fields (like using a fixed timestamp and fixed ID).
2. When serializing, we can remove or normalize non-deterministic fields (but then the contract must allow for that?).
Alternatively, we can have the event class implement a method that returns a version of the event for testing (with deterministic values) or we can use a test data builder that sets fixed values.
We'll assume we have a way to create deterministic events for testing.
How to handle versioning of events?
The contract (schema) should include the version. The golden file should be for a specific version.
Then we must update both when we change the event.
What about backward compatibility?
We might have multiple versions of the same event. Then we need to test each version separately.
So:
code
For each version of an event, we have:
- A schema for that version.
- Golden files for that version.
This strategy can become complex. We must decide on the granularity.
Let's simplify:
code
We are testing the current version of the event. When we change the event (and thus the contract), we update the schema and the golden files for the new version.
We don't test old versions in the same test suite? Maybe we have a separate test suite for old versions (if we still produce them).
Given the complexity, we might want to start with:
code
- One event, one version, one schema, one golden file per scenario.
But the design should allow for multiple versions.
We can parameterize the test with the version.
Example:
code
@ParameterizedTest
@ValueSource(strings = {"v1", "v2"})
public void testOrderCreatedEvent(String version) throws Exception {
// Load schema for the given version: contracts/{version}/order_created_schema.json
// Load golden file for the given version: golden/{version}/order_created/when_order_is_placed.json
// Create an event of the given version? How? We might have different classes for different versions? Or one class with version field?
// We assume we have a way to create an event of a specific version.
// Then:
assertEventConformsToContract(event, schemaFile);
assertEventMatchesGolden(event, goldenFile);
}
But note: the event class might be the same for multiple versions? Then the schema might be the same? Not necessarily.
Alternatively, we can have:
code
We test the event as it is produced by the current code. The current code produces a specific version (maybe the latest). Then we have a contract for that version and golden files for that version.
Old versions are produced by old code (which we don't test in the same suite). So we don't need to parameterize by version.
So we assume:
code
We are testing the current version of the event.
Steps for the test suite:
code
For each event type (and for each scenario of that event):
1. Create the event (with deterministic test data).
2. Validate against the contract (schema) for that event type.
3. Compare the serialized event to the golden file (for that scenario).
If we change the event (and thus the contract), we:
code
- Update the schema file (if the contract changes).
- Update the golden files (if the example event changes).
How to update the golden files?
code
We run the tests with a system property (or environment variable) that enables golden file update.
Example command:
code
mvn test -DupdateGoldenFiles=true
In the test:
code
if (updateGoldenFiles) {
// write the current serialized event to the golden file (overwrite)
} else {
// compare
}
But note: we might have multiple golden files for the same event (different scenarios). We update only the one that is being tested.
This strategy requires discipline:
code
- When we change the contract, we must update the schema and then update the golden files by running the tests with the update flag.
Alternatively, we can have a separate task (like a Maven plugin) that updates all golden files by running the tests and updating. But that might be overkill.
Implementation:
We can create a base class:
code
public abstract class EventTestBase {
private static final String GOLDEN_BASE_PATH = "src/test/resources/golden/events/";
private static final String CONTRACT_BASE_PATH = "src/test/resources/contracts/";
protected void assertEventConformsToContract(Object event, String relativeSchemaPath) throws Exception {
String schemaPath = CONTRACT_BASE_PATH + relativeSchemaPath;
// Load schema from schemaPath (as a JSON schema)
// Convert event to JSON object (using the same serialization as for golden)
// Validate
}
protected void assertEventMatchesGolden(Object event, String relativeGoldenPath) throws Exception {
String goldenPath = GOLDEN_BASE_PATH + relativeGoldenPath;
String canonicalJson = canonicalize(event); // serialize to JSON with sorted keys, etc.
File goldenFile = new File(goldenPath);
if (goldenFile.exists()) {
String goldenJson = readFile(goldenFile);
if (!canonicalJson.equals(goldenJson)) {
if (Boolean.getBoolean("updateGoldenFiles")) {
writeFile(goldenFile, canonicalJson);
} else {
fail("Event does not match golden file. Use -DupdateGoldenFiles to update.");
}
}
} else {
if (Boolean.getBoolean("updateGoldenFiles")) {
writeFile(goldenFile, canonicalJson);
} else {
fail("Golden file does not exist: " + goldenPath);
}
}
}
private String canonicalize(Object event) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// Configure mapper to produce canonical JSON (sorted keys, no whitespace)
mapper.enable(SerializationFeature.INDENT_OUTPUT); // if we want pretty print for golden? But then comparison would fail if we change formatting.
// We might not want indentation for comparison? Let's not indent.
mapper.disable(SerializationFeature.INDENT_OUTPUT);
// But we must sort the keys. Jackson doesn't sort by default. We can use `mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);`
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
return mapper.writeValueAsString(event);
}
// readFile and writeFile helpers...
}
Then in a test:
code
public class OrderCreatedEventTest extends EventTestBase {
@Test
public void testOrderCreatedEvent() throws Exception {
OrderCreatedEvent event = new OrderCreatedEvent(...); // with fixed test data
assertEventConformsToContract(event, "order_created_schema.json");
assertEventMatchesGolden(event, "order_created/when_order_is_placed.json");
}
}
However, note: the contract file path is fixed per event type. We might have multiple contracts for the same event? (e.g., for different versions)
We can adjust:
code
In the test, we specify the contract file and the golden file.
Then in the test we must choose the version. We can have:
code
String version = "v1";
String contractPath = version + "/order_created_schema.json";
String goldenPath = version + "/order_created/when_order_is_placed.json";
Or we can have the version in the event itself and then the test can extract it? But then we are testing the event's version field.
Alternatively, we can have the test for a specific version and the event class is that version. Then we don't need to parameterize.
Given the complexity, let's assume we are testing the current version and we don't have multiple versions in the same codebase.
If we do have multiple versions, we might have different classes for each version? Then we write separate tests for each class.
So:
code
For event class `OrderCreatedV1`:
contract: `contracts/order_created_v1_schema.json`
golden: `golden/order_created_v1/when_order_is_placed.json`
For event class `OrderCreatedV2`:
contract: `contracts/order_created_v2_schema.json`
golden: `golden/order_created_v2/when_order_is_placed.json`
Then we don't need to parameterize, we just have separate test classes.
This is simpler.
Conclusion:
We design:
code
- For each event class (version), we have:
* A JSON schema contract (in `src/test/resources/contracts/`).
* One or more golden files (in `src/test/resources/golden/events/`).
- We write a test class for that event class (or for a specific scenario of that event).
- In the test, we:
1. Create the event (with fixed test data).
2. Validate the event against the contract (schema).
3. Compare the event (in canonical JSON) to the golden file.
- We have a base test class that provides the assertion methods.
This strategy ensures:
code
- The event structure is valid according to the contract.
- The event output is exactly as expected (golden).
However, note: the contract might be more strict than the golden file (the golden file is just one example). So if the contract allows more than what is in the golden, then we are only testing one example.
But that's okay because the contract test ensures the event is valid, and the golden test ensures we don't change the output for that specific scenario.
If we want to test multiple scenarios, we write multiple tests (with different golden files).
One more thing: how to handle events that have collections (arrays) or nested objects?
code
The canonical JSON should sort the keys in objects, but what about arrays? We don't sort arrays because order matters.
So if the event has an array, the order of the array elements must be deterministic in the test.
We must ensure that the test data sets the array in a fixed order.
Also, note that the contract (JSON schema) can validate arrays (minItems, maxItems, item schema, etc.).
So we are covered.
Let's code the base class with:
code
- canonicalize: using Jackson with sorted keys and without indentation.
But note: if the event has a field that is a map, we want the keys sorted. If it has a list, we don't sort the list but the items in the list (if they are objects) must have sorted keys.
Jackson's ORDER_MAP_ENTRIES_BY_KEYS will sort the keys of any map, including nested ones. But it won't sort the elements of a list.
That's fine.
However, if the list contains objects, then each object will have sorted keys. So two events with the same list of objects but in different order of the objects would be considered different (and the golden file would have a specific order). That's what we want.
So we are good.
Now, what about dates? We must have a deterministic way to serialize dates.
code
We can configure the ObjectMapper to use a fixed date format (like ISO-8601) and then set the date fields to fixed values in the test.
So in the test, we create the event with:
code
new OrderCreatedEvent(..., Instant.parse("2020-01-01T00:00:00Z"), ...);
Then the serialization will be deterministic.
Finally, we must be cautious about floating point numbers. We might want to use a fixed precision? But JSON numbers are exact. If we use BigDecimal we can have exact representation. But if we use double, we might have rounding.
We should use BigDecimal for precise numbers in events? Or we can configure the ObjectMapper to use ToNumberGenerator.FLOAT? Not recommended.
It's better to use BigDecimal for monetary values, for example.
In the test, we set the exact value as new BigDecimal("10.00").
Then the serialization will be exact.
So the strategy:
code
- Use deterministic data in tests (fixed timestamps, fixed IDs, fixed numbers as BigDecimal, fixed strings, etc.)
- Serialize with sorted keys and no whitespace.
- Compare the entire JSON string.
This is strict and will catch any change.
But note: if we add a new field that is null, the JSON will include it? By default, Jackson includes nulls. But if we want to ignore nulls, we can configure the ObjectMapper to ignore nulls.
However, the contract (schema) might require the field to be present (non-null) or might allow null. So we must decide.
We want the golden file to represent exactly what is serialized. So if we change the serialization to omit nulls, then the golden file must change.
So we must fix the serialization configuration.
We can have a standard ObjectMapper for event serialization in production and in tests. Then we use the same in the tests.
We can provide the ObjectMapper in the base class.
Alternatively, we can have an EventSerializer class that is used in production and in tests.
Then in the test, we use the same EventSerializer to get the canonical string.
That's better because we are testing the actual serialization.
So:
code
In the base class:
protected String canonicalize(Object event) {
return eventSerializer.serialize(event);
}
where `eventSerializer` is a bean or a static instance that is configured the same as in production.
Then we are sure we are comparing the same format.
Let's adjust:
code
We have an `EventSerializer` that uses the same configuration as in production.
We use that to generate the golden string and to validate the contract? Wait, the contract validation might require the event as a JSON object (map). We can use the same EventSerializer to produce a JSON object (by reading the string) or we can have a method that returns the event as a ` JsonNode`.
Alternatively, we can have:
protected JsonNode toJsonNode(Object event) {
return eventSerializer.serializeToJsonNode(event);
}
Then for contract validation, we use the JsonNode.
And for golden comparison, we use the canonical string.
But note: the contract validation might require the event to be a JSON object. So we can use the same toJsonNode and then convert to a Map or JsonNode for the schema validator.
We'll adjust:
code
In the base class:
private EventSerializer eventSerializer;
@BeforeEach
public void setup() {
eventSerializer = new EventSerializer(); // or inject
}
protected void assertEventConformsToContract(Object event, String relativeSchemaPath) throws Exception {
JsonNode eventNode = eventSerializer.serializeToJsonNode(event);
// Load schema
JsonSchema schema = loadSchema(relativeSchemaPath);
schema.validate(eventNode); // throws if invalid
}
protected void assertEventMatchesGolden(Object event, String relativeGoldenPath) throws Exception {
String canonicalJson = eventSerializer.serializeCanonical(event);
// ... compare with golden file
}
Now, what is serializeCanonical? It should be the same as serializeToJsonNode but as a string with sorted keys and without whitespace.
But note: we might have custom serializers for some types. So we should use the same ObjectMapper that has the custom serializers.
So we configure the ObjectMapper in the EventSerializer with:
code
- Custom serializers/deserializers for our event types (if any).
- The `ORDER_MAP_ENTRIES_BY_KEYS` and without `INDENT_OUTPUT` for canonical.
But wait: for the contract validation, we might not want to use the custom serializers? Because the contract is about the JSON structure, not about how we serialize.
Actually, the contract is the JSON that we produce. So we must validate the JSON that we actually send. So we must use the same serialization.
So we are good.
Now, what about the schema? We have to write the JSON schema for the event. We can generate it from the event class? Or write by hand.
We can write by hand to have control. But then we have to update it when the event changes.
Alternatively, we can generate the schema from the event class (using Jackson's JSON schema module) but that might not be up to date with our custom serializers.
Given the complexity, we might write the schema by hand and keep it in src/test/resources/contracts/.
But then we have to update it when the event changes.
We can have a test that generates the schema from the event class and compares it to the stored schema? That way we ensure the stored schema is up to date.
That's another test: contract schema generation test.
Then when we change the event, we run this test and it will fail, telling us to update the stored schema.
We can run this test with a flag to update the stored schema.
But note: the generated schema might not be exactly what we want (we might want to add descriptions, required fields, etc.). So we might write the schema by hand and then use the generated one as a baseline.
Alternatively, we can use the generated schema and then modify it by hand and then check that the generated one doesn't change in ways we don't want? That's tricky.
Given the complexity, we might decide to write the schema by hand and not generate it.
But then we must remember to update it when the event changes.
We can have a test that validates the event against the stored schema (as we have) and then another test that checks that the stored schema is valid JSON schema? That's trivial.
We can also have a test that checks that the event class (when serialized) matches the stored schema? That's what we are doing in the contract test.
So if the event changes, the contract test will fail because the event doesn't match the stored schema. Then we update the stored schema.
So we don't need a separate test for generating the schema.
However, we might want to ensure that the stored schema is the one we intended. We can have a test that generates the schema and compares it to the stored one, but that might be too strict (because we might have hand-written parts).
Let's not do that.
Summary:
We have:
code
EventTestBase:
- EventSerializer (with configured ObjectMapper)
- assertEventConformsToContract: loads the schema from a file and validates the event (as JsonNode) against it.
- assertEventMatchesGolden: serializes the event to canonical JSON and compares to the golden file, with update option.
Then for each event (and scenario) we write a test that uses these assertions.
We manually update the contract (schema) and golden files when the event changes.
We can also have a test that ensures that the contract (schema) is valid according to the JSON Schema specification? That might be overkill.
But we can have a test that parses the schema and ensures it's valid.
We can do:
code
@Test
public void storedSchemaMustBeValidJsonSchema() throws Exception {
// Load the schema file and try to parse it as a JsonSchema (using a JSON Schema library)
// If it throws, fail.
}
This ensures we didn't break the schema file.
Now, what about multiple events? We can have a test per event per scenario.
Example:
code
OrderCreatedEvent:
test when order is placed -> uses contract: order_created_schema.json, golden: order_created/when_order_is_placed.json
test when order is placed with discount -> uses same contract, different golden: order_created/when_order_is_placed_with_discount.json
We can have a base class for OrderCreatedEvent tests that sets the contract path, then each test method specifies the golden path.
code
public class OrderCreatedEventTest extends EventTestBase {
private static final String CONTRACT_PATH = "order_created_schema.json";
@Test
public void whenOrderIsPlaced_thenEventMatchesGolden() throws Exception {
OrderCreatedEvent event = createOrderCreatedEventWithoutDiscount();
assertEventConformsToContract(event, CONTRACT_PATH);
assertEventMatchesGolden(event, "order_created/when_order_is_placed.json");
}
@Test
public void whenOrderIsPlacedWithDiscount_thenEventMatchesGolden() throws Exception {
OrderCreatedEvent event = createOrderCreatedEventWithDiscount();
assertEventConformsToContract(event, CONTRACT_PATH);
assertEventMatchesGolden(event, "order_created/when_order_is_placed_with_discount.json");
}
}
This works.
Finally, we must consider:
code
- Performance: reading the schema and golden file for every test? We can cache them.
In the base class, we can have:
private Map<String, JsonSchema> schemaCache = new HashMap<>();
protected void assertEventConformsToContract(Object event, String relativeSchemaPath) throws Exception {
JsonSchema schema = schemaCache.computeIfAbsent(relativeSchemaPath, this::loadSchema);
// validate
}
And for golden files, we can cache the content? But golden files might change between runs (if we update). So we should read them every time? Or we can clear the cache when we update.
Alternatively, we can read the golden file every time because it's a small file and we don't run many tests.
But if we have many tests, we can cache the golden content too, but then we must invalidate the cache if we update.
Simpler: read every time.
Error messages: when the golden file doesn't match, we should show a diff.
We can use a diff library (like java-diff-utils) to show the difference.
Or we can just show the two strings.
We can do:
code
Assert.assertEquals(goldenJson, canonicalJson);
But that will show the entire string. We can use a diff.
We can use org.junit.jupiter.api.Assertions.assertEquals which shows a diff for strings? It does, but for large JSON it might be hard.
We can use com.google.common.collect.DiffUtil? Or write a simple diff.
Alternatively, we can use JSONAssert from org.skyscreamer that compares JSON and can ignore order? But we are already canonicalizing.
Actually, we are comparing the canonical strings, so it's a string comparison. We can use assertEquals and it will show the difference.
But if the JSON is large, it's messy.
We can use a JSON diff library that compares two JSON objects and shows the difference in a structured way.
We can do:
code
JsonNode expected = objectMapper.readTree(goldenJson);
JsonNode actual = objectMapper.readTree(canonicalJson);
assertEquals(expected, actual); // JsonNode has equals that compares structure.
But then we lose the canonical string comparison? Actually, if we parse and then compare, we are comparing the structure, but note: the order of keys in objects might be different? We already sorted in canonical, but when we parse, the order might not be preserved? Jackson's JsonNode for objects is a ObjectNode which does not preserve order? Actually, ObjectNode does not guarantee order? But when we serialize with sorted keys, the order is fixed. Then when we parse, the ObjectNode might not have the same order? But the equals method of ObjectNode does not consider order? Let me check: ObjectNode extends ContainerNode and the equals method in ContainerNode uses _children which is a LinkedHashMap? Actually, in Jackson, ObjectNode uses LinkedHashMap to preserve order? I think it does. But let's not rely.
Alternatively, we can use JsonNode.equals which does deep equality and does not require the same order? Actually, uses and the of does consider order? No, does not consider order. Two with the same entries in the same order are equal? Yes, because 's considers order. So if we have two with the same keys in the same order, they are equal. But if the order is different, they are not equal.
So we don't need to parse and compare as JsonNode.
However, if we want to ignore the order of keys in the golden file? We don't, because we canonicalize both.
So we are good.
Let's code the base class with string comparison.
We'll also add a helper to show a diff if the strings are different.
We can use java-diff-utils to generate a unified diff? But that's for text, not JSON.
We can use a JSON-aware diff. But for now, we just show the two strings.
We can improve later.
Steps:
Base class:
code
public abstract class EventTestBase {
private static final String GOLDEN_BASE_PATH = "src/test/resources/golden/events/";
private static final String CONTRACT_BASE_PATH = "src/test/resources/contracts/";
private EventSerializer eventSerializer;
@BeforeEach
public void setUp() {
eventSerializer = new EventSerializer(); // or inject
}
protected void assertEventConformsToContract(Object event, String relativeSchemaPath) throws Exception {
JsonNode eventNode = eventSerializer.serializeToJsonNode(event);
JsonSchema schema = loadSchema(relativeSchemaPath);
schema.validate(eventNode); // throws if invalid
}
protected void assertEventMatchesGolden(Object event, String relativeGoldenPath) throws Exception {
String canonicalJson = eventSerializer.serializeCanonical(event);
File goldenFile = new File(GOLDEN_BASE_PATH + relativeGoldenPath);
if (goldenFile.exists()) {
String goldenJson = readFile(goldenFile).trim();
if (!canonicalJson.equals(goldenJson)) {
if (Boolean.getBoolean("updateGoldenFiles")) {
writeFile(goldenFile, canonicalJson);
} else {
fail("Event does not match golden file. Expected: " + goldenJson + " but was: " + canonicalJson);
}
}
} else {
if (Boolean.getBoolean("updateGoldenFiles")) {
writeFile(goldenFile, canonicalJson);
} else {
fail("Golden file does not exist: " + goldenFile.getAbsolutePath());
}
}
}
private JsonSchema loadSchema(String relativeSchemaPath) throws IOException, JsonMappingException, JsonParseException {
String schemaPath = CONTRACT_BASE_PATH + relativeSchemaPath;
String schemaJson = readFile(new File(schemaPath));
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
return factory.getJsonSchema(schemaJson);
}
private String readFile(File file) throws IOException {
return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
}
private void writeFile(File file, String content) throws IOException {
file.getParentFile().mkdirs();
Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8));
}
}
We need to handle the JSON Schema validation. We can use com.networknt:json-schema-validator or everit:org.json? Let's use com.networknt:json-schema-validator because it's popular.
But note: we are already using Jackson. We can use com.github.fge:json-schema-validator? It's deprecated.
Alternatively, we can use org.everit.json:json-schema? But we are using Jackson's JsonNode.
We can use com.networknt:json-schema-validator which works with Jackson's JsonNode.
Then it will use the version from the $schema property.
We'll use byDefault.
And then:
code
Set<ValidationMessage> errors = schema.validate(eventNode);
if (!errors.isEmpty()) {
fail("Event does not conform to schema. Errors: " + errors);
}
So:
code
protected void assertEventConformsToContract(Object event, String relativeSchemaPath) throws Exception {
JsonNode eventNode = eventSerializer.serializeToJsonNode(event);
JsonSchema schema = loadSchema(relativeSchemaPath);
Set<ValidationMessage> errors = schema.validate(eventNode);
if (!errors.isEmpty()) {
fail("Event does not conform to schema. Errors: " + errors);
}
}
Now, the EventSerializer:
code
public class EventSerializer {
private final ObjectMapper objectMapper;
public EventSerializer() {
objectMapper = new ObjectMapper();
// Configure as needed for our events (custom serializers, modules, etc.)
// For canonical serialization:
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
objectMapper.disable(SerializationFeature.INDENT_OUTPUT);
// Register modules if any (JavaTimeModule, etc.)
}
public String serializeCanonical(Object event) throws JsonProcessingException {
return objectMapper.writeValueAsString(event);
}
public JsonNode serializeToJsonNode(Object event) throws JsonProcessingException {
return objectMapper.valueToTree(event);
}
}
But note: the serializeToJsonNode uses the same ObjectMapper, so it will use the same configuration (like custom serializers).
However, valueToTree will traverse the object and convert to JsonNode. It will use the same serializers.
That's what we want.
We are done.
Summary:
We have a base test class that provides:
code
- Contract validation against a JSON schema.
- Golden file comparison (with update option).
We write one test per event scenario.
We maintain:
code
- JSON schema for each event type (in `src/test/resources/contracts/`).
- Golden files for each scenario (in `src/test/resources/golden/events/`).
We update the golden files and contracts when the event changes.
This strategy ensures that our events:
code
- Are structurally valid (contract).
- Produce the exact expected output (golden) for given scenarios.
And we can catch breaking changes.
However, note: if we change the event in a way that is still valid according to the contract (e.g., adding an optional field) then the golden test will fail because the output changes. We must update the golden file.
That's intentional: we want to review any change.
But what if we add an optional field that is null? Then the canonical JSON might not include it (if we configure the ObjectMapper to omit nulls). Then the golden file doesn't change. So we must be cautious about nulls.
We must decide on serialization configuration:
code
- Omit nulls? Then adding a null field won't change the JSON.
- Include nulls? Then adding a null field will change the JSON.
It's better to include nulls? Because then the absence of a field and a field with null are different.
But in JSON, null is a value. So if we have a field that is null, we should include it? It depends on the contract.
The contract (schema) will specify if the field is required and if it can be null.
We must serialize the event exactly as we do in production.
So we must use the same ObjectMapper configuration as in production.
Therefore, we should not have a separate EventSerializer for tests? We should use the same one as in production.
But then we cannot change it for canonicalization? We need canonicalization for golden comparison (sorted keys, no whitespace). But in production, we might not sort the keys? We might, because we want consistent messages for hashing or signing? It depends.
We must decide:
code
So the base test class:
code
public abstract class EventTestBase {
private static final String GOLDEN_BASE_PATH = "src/test/resources/golden/events/";
private static final String CONTRACT_BASE_PATH = "src/test/resources/contracts/";
private EventSerializer eventSerializer;
@BeforeEach
public void setUp() {
ObjectMapper objectMapper = ObjectMapperProvider.getObjectMapper(); // from production
eventSerializer = new EventSerializer(objectMapper);
}
// ... rest same, but using eventSerializer.serialize(event) for the string.
}
Then we are testing the exact production output.
This is the best.
Now, what if we don't have a production ObjectMapper provider? We can create a configuration in the test that matches production.
But it's better to share the configuration.
If we cannot, then we must duplicate the configuration in the test. And then we must keep them in sync.
So we should share.
Conclusion:
We have designed a testing strategy that:
code
- Uses the same serialization as production (so we are testing the real output).
- Validates against a contract (JSON schema) that we maintain.
- Compares the output to a golden file (exact string) for specific scenarios.
- Allows updating the golden files when we intentionally change the output.
We also have a base class to avoid duplication.
We must write tests for each event scenario.
We must maintain the contracts and golden files.
This is a solid strategy for domain event testing.
Let me know if you have any questions.
I'll architect a comprehensive domain event testing strategy that combines snapshot fixtures, contract tests, and golden assertions for robust event-driven systems.
# .github/workflows/event-tests.yml
name: Domain Event Tests
on:
pull_request:
paths:
- 'src/events/**'
- 'tests/events/**'
- 'tests/golden/**'
- 'tests/contracts/**'
jobs:
event-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run unit tests
run: npm test -- tests/events/*.unit.spec.ts
- name: Run snapshot tests
run: npm test -- tests/events/*.snapshot.spec.ts
- name: Run contract tests
run: npm test -- tests/contracts/
- name: Run golden assertion tests
run: npm test -- tests/events/*.golden.spec.ts
- name: Check for changed golden files
run: |
if git diff --name-only | grep -q 'tests/golden/'; then
echo "::error::Golden files modified. Review changes carefully."
git diff tests/golden/
exit 1
fi
- name: Update golden files (manual trigger only)
if: github.event_name == 'workflow_dispatch'
run: |
npm test -- --update-goldens
git config --global user.email "ci@example.com"
git config --global user.name "CI Bot"
git add tests/golden/
git commit -m "chore: update golden files [skip ci]" || echo "No changes to commit"
git push
C. Makefile Targets:
makefile
test-events:
@echo "Running full event test suite..."
npm test -- tests/events/ tests/contracts/
test-golden-update:
@echo "Updating golden files..."
npm test -- --update-goldens
test-golden-diff:
@echo "Showing golden file diffs..."
git diff tests/golden/
test-contract-validate:
@echo "Validating all contracts against schemas..."
npm test -- tests/contracts/validate-all.spec.ts
test-snapshot:
@echo "Running snapshot tests..."
npm test -- tests/events/*.snapshot.spec.ts
6. Best Practices & Guidelines
A. Golden File Management:
Version golden files: order-created.v1.json, order-created.v2.json
Never auto-update in CI (except manual workflow)
Review all golden changes in PRs
Store in version control (not generated)
Use consistent formatting (2-space indent, sorted keys)
B. Contract Evolution:
typescript
// When contracts change:
// 1. Update schema file
// 2. Add new golden file (v2)
// 3. Keep old golden for backward compatibility tests
// 4. Deprecate old contracts with lifecycle annotations
const OrderCreatedContractV2 = {
...OrderCreatedContract,
title: 'OrderCreatedV2',
properties: {
payload: {
...OrderCreatedContract.properties.payload,
properties: {
...OrderCreatedContract.properties.payload.properties,
shippingAddress: { // New field
type: 'object',
properties: {
street: { type: 'string' },
city: { type: 'string' },
country: { type: 'string' }
},
required: ['street', 'city']
}
}
}
}
};
Generate golden files for existing event scenarios
Add CI pipeline checks
Document golden file update process
Set up monitoring for schema/golden drift
Train team on golden file review process
This strategy provides multiple layers of protection:
Golden files catch exact serialization changes
Contracts ensure structural validity
Snapshots verify aggregate state transitions
CI/CD prevents unintended changes
The combination ensures backward compatibility, contract adherence, and exact output verification while maintaining developer productivity through automated checks and clear failure modes.
ObjectNode
LinkedHashMap
equals
Map
Map
LinkedHashMap
LinkedHashMap
equals
ObjectNode
But we already sorted the keys in the canonical string. So when we parse, the ObjectNode will have the keys in the same order? Not necessarily, because the JSON parser might not preserve the order? Actually, Jackson's ObjectNode uses LinkedHashMap and by default the parser does preserve order? Yes, Jackson preserves order by default.
So we can do:
code
JsonNode expected = objectMapper.readTree(goldenJson);
JsonNode actual = objectMapper.readTree(canonicalJson);
assertEquals(expected, actual);
This will fail if the structure is different, and the error message will show the two JSON trees? Not exactly, it will just say they are not equal.
We can use a JSON diff library to show a better diff.
But for simplicity, we can do:
code
if (!expected.equals(actual)) {
// use a diff library to show the difference
}
We can use com.github.fge.jsondiff.JsonDiff from json-patch library.
Example:
code
String diff = JsonDiff.asJson(expected, actual).toString();
fail("JSON does not match. Diff: " + diff);
But that's an extra dependency.
Alternatively, we can use org.skyscreamer:jsonassert which has a JSONCompare class that can show differences.
Since we are already using JUnit, we can just use assertEquals and if it fails, we can log the two strings.
But note: the strings are the same because we canonicalized? If they are not the same, then the equals on JsonNode might still be true? No, because we canonicalized the string and then parsed. The ObjectNode from the canonical string will have the keys in sorted order. The golden file we read and parse might have a different order? But we stored the golden file in canonical form. So both should have the same order.
So we can just compare the strings:
code
assertEquals(canonicalJson, goldenJson);
And if it fails, we can show the two strings.
But if the golden file is pretty-printed and we are not, then we have a problem. We must store the golden file in the same canonical form (without whitespace). So we must ensure that when we create the golden file (with update), we write the canonical form (without whitespace). Then we compare strings.
So:
code
In `assertEventMatchesGolden`:
if (goldenFile.exists()) {
String goldenJson = readFile(goldenFile).trim(); // in case we have a newline at the end?
if (!canonicalJson.equals(goldenJson)) {
// fail with diff
}
}
And when we write the golden file, we write the canonicalJson (without extra whitespace).
Then the string comparison is exact.
The golden file is an example of the exact JSON that we produce in production for that scenario.
So we must use the same serialization settings as in production.
Therefore, we should not change the ObjectMapper for canonicalization. We use the production ObjectMapper.
Then the golden file will have whatever formatting (with or without whitespace, with or without sorted keys) that we use in production.
But then we must ensure that the production serialization is deterministic? Yes, it must be. Otherwise, we cannot compare.
So we must have deterministic serialization in production.
Rules for deterministic serialization:
- Always write dates in the same format (e.g., ISO-8601).
- Always write numbers in a fixed way (no exponential notation?).
- Always write maps with sorted keys? Not necessarily, but if we don't, then the order might change and the golden comparison will fail.
We have two options:
1. In production, we sort the keys and remove whitespace. Then the golden files are in that format.
2. In the test, we use the production ObjectMapper to serialize, and then we compare the strings exactly. But if the production ObjectMapper does not sort keys, then the order might be non-deterministic (if the map is a HashMap). So we must use a map implementation that preserves order? Or we must sort in the ObjectMapper.
Actually, the event class should not use `HashMap` for fields that are maps? We should use `LinkedHashMap`? Or we should configure the ObjectMapper to sort.
It's better to configure the ObjectMapper to sort the keys. Then the serialization is deterministic.
So in production, we should have:
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
And we should not use `INDENT_OUTPUT`.
Then the production JSON is compact and sorted.
Then the test uses the same ObjectMapper and the golden files are in that format.
So we don't need a special `serializeCanonical` because the production serialization is already canonical.
But wait: what about nested maps? The `ORDER_MAP_ENTRIES_BY_KEYS` sorts only the top-level map? Actually, it sorts all maps? I think it sorts recursively? Let me check: the `SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS` is used by the `MapSerializer` and it will sort the entries of the map. For nested maps, each map will be sorted by its own serializer. So yes, it sorts recursively.
So we are good.
Therefore, we can remove the `serializeCanonical` and just use `objectMapper.writeValueAsString(event)`.
But then we must ensure that the production ObjectMapper is configured exactly the same in the test.
So in the test, we should use the same ObjectMapper as in production.
How?
We can have a Spring configuration that produces the ObjectMapper and then we inject it in the test.
Or we can have a static method in the production code that returns the ObjectMapper.
Let's assume we have a class `ObjectMapperProvider` in production that returns the configured ObjectMapper.
Then in the test:
EventSerializer eventSerializer = new EventSerializer(ObjectMapperProvider.getObjectMapper());
And then:
public class EventSerializer {
private final ObjectMapper objectMapper;
public EventSerializer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public String serialize(Object event) throws JsonProcessingException {
return objectMapper.writeValueAsString(event);
}
public JsonNode serializeToJsonNode(Object event) throws JsonProcessingException {
return objectMapper.valueToTree(event);
}
}
Then we use the same serialization as production.