Java DDD Testing
Scope and authority
Test observable behavior inside the domain layer. The sole technical reference for
this skill is the current C:/git/ddd-example/domain source and tests. Read the
relevant production type and its tests before deriving an expectation. The source
map in Behavioral checks records the inspected
revision and its important variations; recheck the working tree when applying it.
Use real domain objects. No mocks, spies, Mockito extensions, static mocking or
mocked gateways belong in these domain tests. Every unit test method must declare
@DisplayName with a clear description of its behavior. The reference uses no
mocks in its domain tests, but does not yet use @DisplayName; the latter is an
explicit user requirement added to the reference conventions. Mockito in shared
build dependencies does not authorize using it here.
Use this skill to implement tests or review their evidence. For a findings-only
request, report findings and proposed checks without editing application code.
Do not change production behavior merely to satisfy an invented test expectation.
Establish the test contract
- Inspect the selected domain type, factory overload, validator, error type and
existing tests. Identify the rule, inputs and observable result. Do not invent
validation, normalization, uniqueness, idempotency or delivery requirements.
- Inspect
domain/build.gradle, the shared convention, runner and filters. The
reference declares JUnit Jupiter API/engine 5.9.2 and a unitTest tag through
UnitTest. Its Gradle wrapper is 7.6; buildSrc selects Java 17 for itself,
which alone does not declare a domain compiler release. Confirm the target
toolchain; do not upgrade it or add dependencies to use these examples.
- Mirror the production package under
domain/src/test/java, extend the
existing UnitTest, and follow given..._when..._then/should... names, final
locals, expected.../actual... values and JUnit Assertions. Add the required
method-level @DisplayName. Keep setup, action and assertions easy to locate.
- If the reference has alternatives, select the matching one from evidence.
If the target's intended contract is absent or conflicts with the reference,
ask a focused question; continue independent checks. Do not choose a familiar
DDD convention as an unstated replacement.
Match the enforcement boundary
| Subject |
Test the actual behavior |
Category, Video |
Create or update the real object, then call validate(handler). Invalid input is not automatically rejected by the factory/update. |
Genre, CastMember |
Construction and update call selfValidate; assert NotificationException and its errors at that call. Updates mutate before validation, so an exception does not prove unchanged state. |
ThrowsValidationHandler |
The first appended validation error throws DomainException; do not expect every independent error to accumulate. |
Notification |
Validate through the real handler and assert the accumulated Error.message() values. Do not invent error codes or fields. |
| IDs and values |
Follow each concrete equality/null contract. ValueObject does not implement equality; media equality does not include all fields. |
| Local events |
Assert recorded event count, type and payload, or invoke the real entity publication method with a small observing lambda as in EntityTest. This proves local behavior only. |
For exact source locations, boundary choices, collection/copy limitations, exceptions
and utility cases, read Behavioral checks.
For complete source-compatible test examples with @DisplayName, read
JUnit examples when writing or adapting a domain test.
When reproducing the reference test setup, use the complete
UnitTest.java
and Fixture.java
snapshots; their roles and dependencies are in the
test-support prerequisites.
Both are test-support classes without test methods. The optional java-ddd skill's
domain source index locates all 49 production
source files shipped across the family; use it when assembling the examples without
the original checkout. These assets preserve the recorded source revision, not a
claim about a different target's current behavior.
Make each test useful
- One scenario should expose one meaningful behavior: a valid result, a specific
rejected input, a no-op, a copy boundary or an event trigger. Several assertions
may be necessary to establish that result; a test per getter adds no such rule.
- Assert concrete changed and preserved fields, exact error counts/messages used
by the reference, or event payloads. Entity equality checks identity and cannot
establish that an update preserved the right state.
- Pair acceptance and rejection at actual boundaries. Null, blank and trimmed
length are separate validator branches. Do not copy another aggregate's limits
or add a positive-duration rule that
VideoValidator does not contain.
- Capture immutable before-values, not an alias to the same mutable aggregate.
Do not require rollback after
Genre.update or CastMember.update: their source
assigns state before throwing. Characterize it honestly and ask before changing
that behavior.
- Prefer existing project fixtures or direct real-object construction for new tests.
Reuse the reference
Fixture for unrelated valid setup when it already fits the
project, but pin every input that decides the expected result. Its Faker values
are not fixed, and its copy methods do not establish universal deep-copy behavior.
- For update-time tests, reconstruct through the existing
with(...) using fixed
dates in the past; assert advancement from that old updatedAt and preservation
of createdAt. This setup is an explicit user requirement. The source compares
immediate wall-clock values, which need not differ. A no-op can instead assert
an unchanged timestamp. Do not add sleeps, static mocks or a new Clock
production API to make a domain test pass.
- Keep assertions on public behavior. No reflection, private-method verification,
generic test framework or extra production getters solely for a test.
Execute and report
Run the focused test command in the correct module with the supported toolchain,
then the requested domain suite. For this reference, the shared convention supplies
:domain:unitTests and :domain:test; inspect filters before using --tests.
Read discovered/executed counts, failures and skips. Zero executed tests, a compile
failure or a skipped test cannot establish the asserted behavior.
Review every added or changed unit test for @DisplayName, real domain construction
and an expectation that would detect the stated defect. Run the complete examples
when materially changing them; their prerequisites are in the example reference.
No coverage percentage or passing mocked interaction substitutes for the rule.
Report the behavior covered, files changed or findings, exact executed commands and
results, and unresolved gaps. Distinguish source inspection, executed code tests
and written evaluation scenarios. Use Evaluation cases
when reviewing the skill's decisions; written cases are not measured agent results.
Boundaries and handoffs
Gateway interfaces live in the domain, but there is no implementation behavior to
prove by mocking them. Repository adapters, database round trips, transactions,
concurrency conflicts, application orchestration and broker/outbox durability need
their own authorized scope and evidence; they are not domain unit tests. See
Persistence and delivery boundary when
a request mixes these claims with a local domain test.
Compose with java-ddd-aggregates, java-ddd-value-objects,
java-ddd-domain-events, java-ddd-domain-services or java-ddd-repositories
for the corresponding model contract. java-ddd owns domain discovery. Hand off
application work to java-ddd-use-cases and framework tests to
spring-boot-testing; neither changes this skill's domain rules.
1---2name: java-ddd-testing3description: >-4 Write and review Java DDD domain unit tests following the ddd-example domain5 reference: real aggregates and values, validation handlers, typed IDs, exceptions,6 utilities and local domain events. Use when adding a domain behavior test, checking7 validation timing or reviewing assertions that may miss a domain defect. Requires8 no mocks and @DisplayName on every unit test. Does not implement application,9 persistence, Spring or message-delivery tests.10metadata:11 source: https://skillmd.com/skills/robsonkades/java-ddd-testing12---1314# Java DDD Testing1516## Scope and authority1718Test observable behavior inside the domain layer. The sole technical reference for19this skill is the current `C:/git/ddd-example/domain` source and tests. Read the20relevant production type and its tests before deriving an expectation. The source21map in [Behavioral checks](references/behavioral-checks.md) records the inspected22revision and its important variations; recheck the working tree when applying it.2324Use real domain objects. **No mocks, spies, Mockito extensions, static mocking or25mocked gateways belong in these domain tests. Every unit test method must declare26`@DisplayName` with a clear description of its behavior.** The reference uses no27mocks in its domain tests, but does not yet use `@DisplayName`; the latter is an28explicit user requirement added to the reference conventions. Mockito in shared29build dependencies does not authorize using it here.3031Use this skill to implement tests or review their evidence. For a findings-only32request, report findings and proposed checks without editing application code.33Do not change production behavior merely to satisfy an invented test expectation.3435## Establish the test contract36371. Inspect the selected domain type, factory overload, validator, error type and38 existing tests. Identify the rule, inputs and observable result. Do not invent39 validation, normalization, uniqueness, idempotency or delivery requirements.402. Inspect `domain/build.gradle`, the shared convention, runner and filters. The41 reference declares JUnit Jupiter API/engine 5.9.2 and a `unitTest` tag through42 `UnitTest`. Its Gradle wrapper is 7.6; `buildSrc` selects Java 17 for itself,43 which alone does not declare a domain compiler release. Confirm the target44 toolchain; do not upgrade it or add dependencies to use these examples.453. Mirror the production package under `domain/src/test/java`, extend the46 existing `UnitTest`, and follow `given..._when..._then/should...` names, `final`47 locals, `expected...`/`actual...` values and JUnit `Assertions`. Add the required48 method-level `@DisplayName`. Keep setup, action and assertions easy to locate.494. If the reference has alternatives, select the matching one from evidence.50 If the target's intended contract is absent or conflicts with the reference,51 ask a focused question; continue independent checks. Do not choose a familiar52 DDD convention as an unstated replacement.5354## Match the enforcement boundary5556| Subject | Test the actual behavior |57| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |58| `Category`, `Video` | Create or update the real object, then call `validate(handler)`. Invalid input is not automatically rejected by the factory/update. |59| `Genre`, `CastMember` | Construction and `update` call `selfValidate`; assert `NotificationException` and its errors at that call. Updates mutate before validation, so an exception does not prove unchanged state. |60| `ThrowsValidationHandler` | The first appended validation error throws `DomainException`; do not expect every independent error to accumulate. |61| `Notification` | Validate through the real handler and assert the accumulated `Error.message()` values. Do not invent error codes or fields. |62| IDs and values | Follow each concrete equality/null contract. `ValueObject` does not implement equality; media equality does not include all fields. |63| Local events | Assert recorded event count, type and payload, or invoke the real entity publication method with a small observing lambda as in `EntityTest`. This proves local behavior only. |6465For exact source locations, boundary choices, collection/copy limitations, exceptions66and utility cases, read [Behavioral checks](references/behavioral-checks.md).67For complete source-compatible test examples with `@DisplayName`, read68[JUnit examples](references/examples.md) when writing or adapting a domain test.69When reproducing the reference test setup, use the complete70[UnitTest.java](assets/domain/src/test/java/com/robsonkades/admin/catalogo/domain/UnitTest.java)71and [Fixture.java](assets/domain/src/test/java/com/robsonkades/admin/catalogo/domain/Fixture.java)72snapshots; their roles and dependencies are in the73[test-support prerequisites](references/examples.md#test-support-source-and-prerequisites).74Both are test-support classes without test methods. The optional `java-ddd` skill's75[domain source index](../java-ddd/references/source-index.md) locates all 49 production76source files shipped across the family; use it when assembling the examples without77the original checkout. These assets preserve the recorded source revision, not a78claim about a different target's current behavior.7980## Make each test useful8182- One scenario should expose one meaningful behavior: a valid result, a specific83 rejected input, a no-op, a copy boundary or an event trigger. Several assertions84 may be necessary to establish that result; a test per getter adds no such rule.85- Assert concrete changed and preserved fields, exact error counts/messages used86 by the reference, or event payloads. Entity equality checks identity and cannot87 establish that an update preserved the right state.88- Pair acceptance and rejection at actual boundaries. Null, blank and trimmed89 length are separate validator branches. Do not copy another aggregate's limits90 or add a positive-duration rule that `VideoValidator` does not contain.91- Capture immutable before-values, not an alias to the same mutable aggregate.92 Do not require rollback after `Genre.update` or `CastMember.update`: their source93 assigns state before throwing. Characterize it honestly and ask before changing94 that behavior.95- Prefer existing project fixtures or direct real-object construction for new tests.96 Reuse the reference `Fixture` for unrelated valid setup when it already fits the97 project, but pin every input that decides the expected result. Its Faker values98 are not fixed, and its copy methods do not establish universal deep-copy behavior.99- For update-time tests, reconstruct through the existing `with(...)` using fixed100 dates in the past; assert advancement from that old `updatedAt` and preservation101 of `createdAt`. This setup is an explicit user requirement. The source compares102 immediate wall-clock values, which need not differ. A no-op can instead assert103 an unchanged timestamp. Do not add sleeps, static mocks or a new `Clock`104 production API to make a domain test pass.105- Keep assertions on public behavior. No reflection, private-method verification,106 generic test framework or extra production getters solely for a test.107108## Execute and report109110Run the focused test command in the correct module with the supported toolchain,111then the requested domain suite. For this reference, the shared convention supplies112`:domain:unitTests` and `:domain:test`; inspect filters before using `--tests`.113Read discovered/executed counts, failures and skips. Zero executed tests, a compile114failure or a skipped test cannot establish the asserted behavior.115116Review every added or changed unit test for `@DisplayName`, real domain construction117and an expectation that would detect the stated defect. Run the complete examples118when materially changing them; their prerequisites are in the example reference.119No coverage percentage or passing mocked interaction substitutes for the rule.120121Report the behavior covered, files changed or findings, exact executed commands and122results, and unresolved gaps. Distinguish source inspection, executed code tests123and written evaluation scenarios. Use [Evaluation cases](references/evaluation-cases.md)124when reviewing the skill's decisions; written cases are not measured agent results.125126## Boundaries and handoffs127128Gateway interfaces live in the domain, but there is no implementation behavior to129prove by mocking them. Repository adapters, database round trips, transactions,130concurrency conflicts, application orchestration and broker/outbox durability need131their own authorized scope and evidence; they are not domain unit tests. See132[Persistence and delivery boundary](references/persistence-and-delivery.md) when133a request mixes these claims with a local domain test.134135Compose with `java-ddd-aggregates`, `java-ddd-value-objects`,136`java-ddd-domain-events`, `java-ddd-domain-services` or `java-ddd-repositories`137for the corresponding model contract. `java-ddd` owns domain discovery. Hand off138application work to `java-ddd-use-cases` and framework tests to139`spring-boot-testing`; neither changes this skill's domain rules.