Org Skills
Referenceaem-testing

AEM Mocks cookbook

Supporting material for aem-testing. Agents load it on demand; it ships inside the skill folder.

RawSource

Verified: 2026-09 against https://wcm.io/testing/aem-mock/ and https://sling.apache.org/documentation/development/sling-mock.html

Open this for the exact API to build content, stub a query, register a service, or configure the context.

Choosing a ResourceResolverType

Type Use when Cost
RESOURCERESOLVER_MOCK (default) Models, servlets and services that use only the Sling API Milliseconds; no JCR Node/Session, no real queries
JCR_MOCK The code adapts to Node or Session In-memory JCR; queries return only what you stub
JCR_OAK Real queries, node types, ACLs, versioning Seconds per context — confine it to a couple of classes
NONE Pure OSGi wiring No repository at all

Pick the lightest type that exercises the path. Switching the whole suite to JCR_OAK to make one test pass hides a design problem and makes the suite one nobody runs locally.

Configuring the context

@ExtendWith({AemContextExtension.class, MockitoExtension.class})
class PriceServiceImplTest {

    private final AemContext context = new AemContextBuilder(ResourceResolverType.JCR_MOCK)
        .plugin(CORE_COMPONENTS)                       // core.wcm.components.testing.aem-mock-plugin
        .beforeSetUp(ctx -> { /* register services the model needs */ })
        .build();
}

A plain new AemContext() is RESOURCERESOLVER_MOCK and is the right default. AemContextBuilder is for when you need a different resolver type, a plugin, or setup that must run before the context starts.

Testing a component that delegates to a Core Component needs the Core Components test dependency (core.wcm.components.testing.aem-mock-plugin) so the delegate's models are registered; without it, @Via(ResourceSuperType.class) injects null and every assertion fails confusingly.

Building content

// from a JSON fixture — the default for component tests
context.load().json("/com/acme/core/models/TeaserModelTest.json", "/content/acme");

// programmatically, when the shape is simpler than a fixture
Page page = context.create().page("/content/acme/en", "/conf/acme/settings/wcm/templates/page",
                                  Map.of("jcr:title", "English Home"));
Resource teaser = context.create().resource(page, "jcr:content/root/teaser",
    Map.of("sling:resourceType", "acme/components/teaser", "title", "Spring release"));
Asset asset = context.create().asset("/content/dam/acme/hero.jpg", 1200, 800, "image/jpeg");
context.create().tag("acme:news");

Keep one JSON fixture per test class, next to it in src/test/resources, holding one resource per scenario: fully authored, empty, partially authored, invalid. That fixture is how you cover the dialog: every dialog field should appear both authored and missing somewhere in it.

Content Fragments have no context.create().contentFragment(...) builder. Load them as JSON like any other content — export a real fragment's .json from an instance, trim it, and check it in as a fixture, then adapt the resource to ContentFragment.

Stubbing a query

With JCR_MOCK, queries return nothing unless you say what they return:

MockJcr.setQueryResult(context.resourceResolver().adaptTo(Session.class),
                       List.of(node1, node2));

// or scoped to one statement and language:
MockJcr.setQueryResult(session, "SELECT * FROM [cq:Page] WHERE …", Query.JCR_SQL2,
                       List.of(node1));

This tests the code around the query — the mapping, the paging, the null handling. It does not test that the query is correct or indexed; that belongs in an integration test, and the index itself belongs in an Explain Query check (aem-performance).

Content policies and context-aware configuration

context.contentPolicyMapping("acme/components/teaser",
    "showDescription", true, "allowedHeadingElements", new String[]{"h2", "h3"});

This is far cheaper than hand-building a /conf policy tree, and it is what @ScriptVariable private Style currentStyle reads.

For Sling Context-Aware Configuration, register the mock plugin and write the configuration resource under /conf/<site>/sling:configs/<name>.

Registering services

context.registerService(Replicator.class, replicatorMock);
PriceService service = context.registerInjectActivateService(new PriceServiceImpl(),
        Map.of("endpoint", "https://test.invalid", "timeout", 500));

registerInjectActivateService performs real Declarative Services injection and calls @Activate. Mandatory references must be registered first — if they are not, the call fails, and that failure is a genuine test of your component's wiring.

Mock outbound collaborators (HTTP clients, JobManager, Replicator) with Mockito and verify the interaction. Do not mock Resource, ValueMap, Page or ResourceResolver: AEM Mocks gives you real implementations, and a Mockito Resource will happily return values production never would.

Servlets and requests

context.currentResource("/content/acme/en/jcr:content/product");
context.requestPathInfo().setSelectorString("prices");
context.requestPathInfo().setExtension("json");
context.request().setQueryString("currency=EUR");

servlet.doGet(context.request(), context.response());

assertEquals(200, context.response().getStatus());
assertEquals("application/json", context.response().getContentType());
JsonNode body = new ObjectMapper().readTree(context.response().getOutputAsString());

Cover the error paths in the same class: a bad selector or parameter → 400, a missing resource → 404, a downstream failure → a 5xx with no stack trace in the body.

Jobs, workflows and filters

  • JobConsumer: build a mock Job with properties and assert the JobResult for success, retryable failure and permanent failure.
  • WorkflowProcess: mock WorkItem, WorkflowData (with the payload path) and a MetaDataMap for the process arguments, then run against AEM Mocks content.
  • Filters: call doFilter with a Mockito FilterChain and verify whether the chain was continued.

Determinism

Inject a Clock (or a time provider) rather than calling new Date() in the code under test; fix Locale and TimeZone in any test that formats. No network, no Thread.sleep, no order dependence — the extension gives each test a fresh AemContext, so nothing should leak between them.