AEM ENGINEERING / 005
Testing Sling Models Beyond the Happy Path
Test Sling Model adaptation failures, required injections, optional content and service boundaries with JUnit 5 and AEM Mocks, then validate them in AEM.
Topic map
Test the adaptation contract
Sling Model failure-path testing
- 01Fixture
- 02Adaptable
- 03Injection
- 04Behavior
- 05Runtime boundary
SYSTEM OVERVIEW
A test pyramid with explicit boundaries.
Use the cheapest test that exercises the contract; a mock success is not evidence of deployment correctness.
Unit / AEM Mock
- Resource fixture
- Adaptable + injected values
- Model behavior
Runtime integration
- Deployed bundle
- Real services + adapters
- Request / repository behavior
THIS ARTICLE EXPLORES
- Define absent-data behavior before writing assertions.
- Test adaptation separately from business logic.
- Know where mocks stop representing the runtime.
01 / CONTRACT
Test the model's contract, not its getters
Start by writing down what makes the model valid. Which authored fields are required? Which dependencies must be available? What should an empty optional field render? A suite that only compares a getter with the same fixture value can miss the failures that actually break a page.
Separate content absence from operational failure. A missing optional image might produce no image markup. A required pricing service that cannot be injected is a different condition. Making every injection optional merely to get a green test hides that distinction.
02 / ADAPTATION
Make failed adaptation observable
Sling's adaptTo() contract returns null when adaptation fails; ModelFactory.createModel() exposes exceptions. Use ModelFactory when a test needs to distinguish missing injections from an invalid adaptable or initialization failure. Match the adaptable declared by the model: a request-backed model is not interchangeable with a resource-backed model.
Use the dependency versions compatible with your AEM target. The downloadable fixture is resource-adaptable with a required title and LabelService, plus an optional subtitle. It tests a local mock context, not a deployed repository. Keep each test's fixture independent.
FILE · src/main/java/com/mohammedboudoun/lab/models/TeaserModel.java
javapackage com.mohammedboudoun.lab.models;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.InjectionStrategy;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
@Model(adaptables = Resource.class)
public class TeaserModel {
@ValueMapValue
private String title;
@ValueMapValue(injectionStrategy = InjectionStrategy.OPTIONAL)
private String subtitle;
@OSGiService
private LabelService labels;
public String getHeading() { return labels.format(title); }
public String getSubtitle() { return subtitle == null ? "" : subtitle; }
}
Locate the failure boundary
Differentiate a missing adaptable, injection failure and a valid model returning an empty result.
- 01Resource or request
- 02Adapter registration
- 03Injection contract
- 04Post-construction
- 05Observable result
03 / REPRODUCIBLE LAB
Run the adaptation contract tests
The source below was compiled and all six tests passed in the recorded local environment. Each test creates its own AemContext. The required service is registered only when that case needs it, so the missing-service test cannot pass because of a shared fixture.
The failing-adaptation case is a passing test: it asserts the expected exception and null-return contract. It is not an unresolved build failure. Optional content has an explicit fallback; required inputs remain required.
Six adaptation contracts, exercised locally
A minimal Java/Maven fixture with JUnit 5 and AEM Mocks. Inspect the resource-adaptable model, vary required inputs and observe failure behavior without a running AEM instance.
Recorded validation:
ENVIRONMENT / RECORDED VERSIONS
- Java / OS
- Oracle JDK 17.0.12 · macOS aarch64 · Java 17 compilation
- Maven
- 3.8.6
- Mock classpath
- Sling Models implementation 1.4.14 (resolved during the recorded run)
- Tests
- JUnit Jupiter 5.10.2 · AEM Mocks JUnit 5 5.6.10
- Compile API
- AEM Uber Jar 6.5.17 (provided; no AEM runtime)
- Plugins
- Compiler 3.11.0 · Surefire 3.2.5 · Jar 3.3.0
SETUP / REQUIREMENTS
- Install JDK 17 and Maven; verify java -version and mvn -version select that JDK. Only the recorded environment was tested.
- Download and extract the source ZIP; open a terminal in sling-model-contracts.
- Allow Maven Central access for dependency resolution. The included settings.xml contains no credentials or private repositories; corporate networks may need approved proxy settings.
- No AEM server, SDK installation, credentials or external API is required. The API dependency is downloaded by Maven, not bundled in the ZIP.
RUN
mvn -s settings.xml -B verifyVALIDATES
- Required title and present optional subtitle adapt through ModelFactory.
- Missing required title raises MissingElementsException.
- Absent optional subtitle yields the model’s explicit empty-string fallback.
- A registered service test double receives the authored title and supplies the returned heading.
- Missing required service raises MissingElementsException; Resource.adaptTo returns null.
- A request supplied to this resource-only model raises InvalidAdaptableException.
DOES NOT VALIDATE
- Deployment or compatibility with any AEM release, including the version named by the compile-time API.
- Real OSGi DS activation, bundle resolution, service-user mappings or repository ACLs.
- Oak query plans, HTL output, JSON exporter contracts, Dispatcher or performance.
- Every malformed value or service-exception path; the optional fixture is a property, not a child resource.
CAPTURED OUTPUT / EXCERPT
CHECK happy-path: title and optional subtitle mapped
CHECK wrong-adaptable: request rejected by resource-only model
CHECK missing-service: factory exception; adaptTo returns null
CHECK required-title: ModelFactory throws MissingElementsException
CHECK optional-subtitle: adaptation succeeds with empty fallback
CHECK service-double: injected service called with authored title
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESSSOURCE NOTES / VALIDATION BOUNDARY
Captured from a local Maven run on macOS aarch64 with Oracle JDK 17.0.12 and Maven 3.8.6. CHECK lines follow assertions. Other Maven lines omitted; test order is not an API contract.
The ZIP contains source, setup, pinned direct dependencies and evidence.json. Its source hashes are checked during packaging; changed Java/POM/settings inputs require fresh evidence.
The lambda is a deterministic service double in the mock registry, not a deployed OSGi component. AEM Mocks uses its transitive Sling implementation; align dependencies separately with a real application target.
Surefire writes each reader’s own results under target/surefire-reports. No public GitHub repository is claimed.
FILE · TeaserModelTest.java — missing service excerpt
java@Test
void missingServiceShowsBothFailureContracts() {
Resource resource = context.create().resource("/content/no-service", "title", "AEM");
assertThrows(MissingElementsException.class, () -> factory.createModel(resource, TeaserModel.class));
assertNull(resource.adaptTo(TeaserModel.class));
System.out.println("CHECK missing-service: factory exception; adaptTo returns null");
}04 / FIXTURES
Keep fixtures smaller than the failure
AEM Mocks provides an AemContext and JUnit 5 extension for registering models, creating resources and supplying services. Prefer a minimal resource tree for behavior tests, then add a small number of representative JSON fixtures when hierarchy matters. A large copied content export makes accidental dependencies difficult to notice.
For a request model, set the current resource and request inputs explicitly before adaptation. Register a deterministic service double when the model delegates to a service; do not reach a real HTTP endpoint from a model unit test. Test the service's timeout behavior separately from the model's handling of its result.
- Required property missing: fail adaptation or surface a deliberately specified error.
- Optional child missing: return the documented empty state.
- Malformed authored value: reject, normalize or fall back according to an explicit contract.
- Required OSGi service absent: verify adaptation fails instead of silently inventing data.
- Service returns empty or throws: test the UI-facing behavior without suppressing diagnostics.
| Fixture | Contract to assert | False confidence to avoid |
|---|---|---|
| Property absent | Required failure or explicit fallback. | Only testing a fully populated fixture. |
| Optional child missing | Stable empty behavior. | Mock accidentally supplies it. |
| Service unavailable | Intended failure boundary. | Always registering every dependency. |
| Wrong adaptable | Expected adaptation outcome. | Calling constructors instead of adapting. |
05 / RUNTIME
Know what mocks cannot prove
A passing unit test does not establish bundle resolution, service-user mappings, actual ACLs, Dispatcher behavior or an Oak query plan. Choose the mock resolver type intentionally and retain an integration test for assumptions that depend on the repository or deployed OSGi environment.
For an upgrade, use the same content contract tests before and after the dependency change, then validate runtime wiring in the target AEM installation. The AEM 6.5 LTS case study explains why application tests and platform compatibility are complementary evidence.
06 / REVIEW
Review failures as part of the release
Make assertion messages explain the intended behavior. Avoid assertions on private field names or the number of internal helper calls unless those calls define a resource or performance contract. Refactoring should not require rewriting tests that describe unchanged behavior.
Repository ownership deserves a separate check: the ResourceResolver lifecycle note covers cleanup and request scope. When a dependency exists in the unit fixture but not in AEM, follow the OSGi diagnostic sequence rather than adding more mocks.
- Run isolated model tests in the build before packaging.
- Validate JSON exporter shape if a frontend consumes the model as an API.
- Exercise missing and malformed content in an author/publish integration environment.
- Document which runtime guarantees remain outside the unit suite.
REFERENCE DESK
Sources & further verification
Product behavior should be checked against the target AEM and search-engine release. The design choices in this note are proposed assessment criteria, not vendor guarantees.
Standards / primary sources
- wcm.io — dependency versions and target alignment (external, opens in a new tab)
- Apache Sling — Models, injection and ModelFactory (external, opens in a new tab)
- wcm.io — AEM Mocks usage and JUnit 5 integration (external, opens in a new tab)
- Apache Sling — ModelFactory exceptions (external, opens in a new tab)