Unit Testing AEM with JUnit 5 and AEM Mocks

A Sling Model that works on your laptop can still break on the author tier, and the first place you usually find out is a failed Cloud Manager build. Unit tests shorten that loop. They run in seconds on your machine, they exercise your code against a mocked AEM runtime, and they produce the coverage data that the build pipeline checks.

In this lesson you set up JUnit 5 and AEM Mocks in the core module of a mysite project, then write tests for a Sling Model, an OSGi service and a servlet. You run the tests with Maven, read the failures, and add a JaCoCo report so you can see which lines are covered before you push.

The test code follows the archetype’s conventions, so you can compare it with the classes that the generated project already contains.

Table of contents

Unit Testing AEM with JUnit 5 and AEM Mocks - AEMCQ5Tutorials

Why this matters

Most AEM bugs that reach production are logic bugs in models and services: a null check missing on a property, a path that is built with the wrong separator, or a default that is never applied. These are cheap to catch with a unit test and expensive to find on an author instance. A test suite also documents what a model is supposed to return, which helps the next developer who inherits the code.

Who should read this

This lesson is for developers who write Sling Models, OSGi services and servlets in AEM as a Cloud Service, and for team leads who want their Cloud Manager builds to pass the code quality stage without last-minute test work.

Prerequisites

What AEM Mocks gives you

AEM Mocks is an open source library from wcm.io. It builds on the Sling Mocks framework and provides an in-memory repository, a fake OSGi container, and AEM-specific helpers such as page managers and request objects. The JUnit 5 integration is io.wcm.testing.aem-mock.junit5. Your tests get an AemContext object, which you use to create content, register services and call your code.

AEM Mocks does not run the real AEM product. Replication, workflows and the Dispatcher are not covered by it. Use it to test your logic, and use integration tests for the behaviour of the running instance.

The context also decides which repository your test uses. Pick the lightest type that your code needs:

ResourceResolverTypeWhat you getWhen to use it
RESOURCERESOLVER_MOCK (default)Sling resources in memory, no JCRMost models, services and servlets. It is the fastest option.
JCR_MOCKA mocked JCR session, without queries or observationCode that adapts to Node or Session.
JCR_OAKA real in-memory Oak repository, with queriesCode that runs JCR-SQL2 or QueryBuilder queries. Add the org.apache.sling:org.apache.sling.testing.sling-mock-oak test dependency. Tests are slower.

The archetype’s AppAemContext has an overload that takes the type, for example AppAemContext.newAemContextBuilder(ResourceResolverType.JCR_OAK).

Hands-on: write the tests

The steps below use the mysite project and the com.mysite.core package. Run every command from the project root unless a step says otherwise.

Step 1: Check the test dependencies

Open core/pom.xml and confirm the test-scoped dependencies below. The archetype adds them without a <version>, because the root pom.xml manages the versions in dependencyManagement. In the current archetype these are JUnit BOM 5.8.2, Mockito 4.1.0, AEM Mocks 5.5.4 and the Context-Aware Configuration mock plugin 1.4.0. The versions change between archetype releases, so check your own root POM rather than copying these.

<!-- core/pom.xml (test dependencies; versions are managed in the root pom.xml) -->
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>io.wcm</groupId>
  <artifactId>io.wcm.testing.aem-mock.junit5</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.testing.caconfig-mock-plugin</artifactId>
  <scope>test</scope>
</dependency>

The archetype also adds mockito-core, junit-addons and the Core Components test plugin (core.wcm.components.testing.aem-mock-plugin), which AppAemContext uses in the next step. The aem-sdk-api dependency is provided, and its version comes from the aem.sdk.api property. Do not add a <version> to a test dependency in core/pom.xml. Change it in the root POM, so that every module uses the same JUnit and Mockito versions.

Step 2: Create the shared test context

Create one helper that builds the AemContext with the plugins your project uses. The archetype does this in AppAemContext, under core/src/test/java/com/mysite/core/testcontext. Keep the plugins in one place, so that each test class does not repeat them.

package com.mysite.core.testcontext;

import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextBuilder;

import static com.adobe.cq.wcm.core.components.testing.mock.ContextPlugins.CORE_COMPONENTS;
import static org.apache.sling.testing.mock.caconfig.ContextPlugins.CACONFIG;

public final class AppAemContext {

    private AppAemContext() {
        // static methods only
    }

    public static AemContext newAemContext() {
        return newAemContextBuilder().build();
    }

    public static AemContextBuilder newAemContextBuilder() {
        return new AemContextBuilder()
            .plugin(CACONFIG)
            .plugin(CORE_COMPONENTS)
            .afterSetUp(context -> context.addModelsForPackage("com.mysite.core.models"));
    }
}

The archetype generates the same class with the Context-Aware Configuration and Core Components plugins and an empty set-up callback. The only addition here is addModelsForPackage. AEM Mocks also registers the models listed in the bundle manifest that bnd writes during the Maven build, but registering the package explicitly means the tests also work when your IDE compiles the classes without Maven.

The afterSetUp callback runs once for every test method. Use it to register model packages and default content. Do not put test data here that only one class needs.

Step 3: Test a Sling Model

Test the models the way the framework runs them. The model below reads jcr:title and falls back to a default when the title is blank. It is adaptable from Resource, so the test creates a resource, adapts it and asserts the result.

The archetype generates a larger HelloWorldModel, which builds a message from the resource type and the current page, and a matching testGetMessage test. For this lesson, replace both with the short versions below, so that each test maps to one branch of the code. If you want to keep the generated files, create the model under another name, such as TitleModel, and rename the test to match.

package com.mysite.core.models;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class HelloWorldModel {

    @ValueMapValue(name = "jcr:title")
    private String title;

    public String getTitle() {
        return title != null && !title.trim().isEmpty() ? title : "Hello World";
    }
}
package com.mysite.core.models;

import com.mysite.core.testcontext.AppAemContext;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@ExtendWith(AemContextExtension.class)
class HelloWorldModelTest {

    private final AemContext context = AppAemContext.newAemContextBuilder().build();

    @Test
    void returnsTitleFromResource() {
        context.create().resource("/content/mysite/us/en", "jcr:title", "Home");
        HelloWorldModel model = context.resourceResolver().getResource("/content/mysite/us/en")
            .adaptTo(HelloWorldModel.class);
        assertNotNull(model);
        assertEquals("Home", model.getTitle());
    }

    @Test
    void returnsDefaultWhenTitleIsMissing() {
        context.create().resource("/content/mysite/empty", "jcr:primaryType", "nt:unstructured");
        HelloWorldModel model = context.resourceResolver().getResource("/content/mysite/empty")
            .adaptTo(HelloWorldModel.class);
        assertNotNull(model);
        assertEquals("Hello World", model.getTitle());
    }
}

The first test checks the happy path. The second checks the default, which is the case that most often breaks in production because nobody filled in the field. Write one test for each branch in the model. Adapt from the resource that the production code passes in, not from the request, so the test follows the real call path.

When a test needs more than a few properties, keep the content in a JSON file under core/src/test/resources and load it, rather than building it line by line:

// core/src/test/resources/com/mysite/core/models/HelloWorldModelTest.json
context.load().json("/com/mysite/core/models/HelloWorldModelTest.json", "/content/mysite/us/en");

To create that JSON, export a real page with .infinity.json on a local SDK instance and remove the properties the test does not need.

Step 4: Test an OSGi service

Register the implementation in the test context, then ask the context for the service through its interface. Test the service as a plain object. Use Mockito only for the dependencies that are outside your bundle, such as an external API client.

The archetype does not contain a service like this, so create the interface and the implementation first. The fallback name comes from an OSGi configuration, which gives you a third case to test.

package com.mysite.core.services;

public interface GreetingService {

    String greet(String name);
}
package com.mysite.core.services.impl;

import com.mysite.core.services.GreetingService;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;

@Component(service = GreetingService.class)
@Designate(ocd = GreetingServiceImpl.Config.class)
public class GreetingServiceImpl implements GreetingService {

    @ObjectClassDefinition(name = "MySite - Greeting Service")
    public @interface Config {

        @AttributeDefinition(name = "Fallback name")
        String fallback_name() default "guest";
    }

    private String fallbackName = "guest";

    @Activate
    protected void activate(Config config) {
        fallbackName = config.fallback_name();
    }

    @Override
    public String greet(String name) {
        String who = name == null || name.trim().isEmpty() ? fallbackName : name.trim();
        return "Hello, " + who;
    }
}

The test registers the implementation and checks all three cases: a name, a blank name and a configured fallback.

package com.mysite.core.services.impl;

import com.mysite.core.services.GreetingService;
import com.mysite.core.testcontext.AppAemContext;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertEquals;

@ExtendWith(AemContextExtension.class)
class GreetingServiceImplTest {

    private final AemContext context = AppAemContext.newAemContextBuilder().build();

    @Test
    void greetsByName() {
        context.registerInjectActivateService(new GreetingServiceImpl());
        GreetingService service = context.getService(GreetingService.class);
        assertEquals("Hello, Ankur", service.greet("Ankur"));
    }

    @Test
    void usesFallbackForBlankName() {
        context.registerInjectActivateService(new GreetingServiceImpl());
        GreetingService service = context.getService(GreetingService.class);
        assertEquals("Hello, guest", service.greet("  "));
    }

    @Test
    void usesConfiguredFallback() {
        context.registerInjectActivateService(new GreetingServiceImpl(), "fallback.name", "visitor");
        GreetingService service = context.getService(GreetingService.class);
        assertEquals("Hello, visitor", service.greet(null));
    }
}

registerInjectActivateService injects references and runs the @Activate method. The extra key-value pairs in the third test are the OSGi configuration. The element fallback_name() becomes the property fallback.name, because OSGi turns an underscore in a configuration element name into a dot. When you omit the pairs, the defaults from the Config annotation apply.

Step 5: Test a servlet

Servlets are the hardest part to test by hand because they depend on the request and response objects. AEM Mocks gives you mock request and response objects through context.request() and context.response(). Set the resource that the servlet expects, call the servlet, and then read the output.

The archetype’s SimpleServlet is registered for the mysite/components/page resource type and the txt extension. It writes Title = followed by the jcr:title of the current resource, as plain text. The test below checks both the content type and the output.

package com.mysite.core.servlets;

import com.mysite.core.testcontext.AppAemContext;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@ExtendWith(AemContextExtension.class)
class SimpleServletTest {

    private static final String PAGE_CONTENT = "/content/mysite/us/en/jcr:content";

    private final AemContext context = AppAemContext.newAemContext();

    @Test
    void writesTitleOfCurrentResource() throws Exception {
        context.create().resource(PAGE_CONTENT,
            "sling:resourceType", "mysite/components/page",
            "jcr:title", "Home");
        context.currentResource(PAGE_CONTENT);

        new SimpleServlet().doGet(context.request(), context.response());

        assertTrue(context.response().getContentType().startsWith("text/plain"));
        assertEquals("Title = Home", context.response().getOutputAsString());
    }
}

context.currentResource() sets the resource on the mock request, which is where the servlet reads it from. Set it before you call the servlet. The test lives in the servlet’s package, so it can call the protected doGet method directly, without a servlet container or Sling’s resolution of the URL. Resolution by resource type, selector and extension is the job of integration tests.

Step 6: Run the tests and read failures

Run the core module tests from the project root. Use the -pl option so that Maven only builds core, which is faster while you work.

# all tests in core
mvn -pl core clean test

# one class
mvn -pl core test -Dtest=HelloWorldModelTest

# one method
mvn -pl core test -Dtest=HelloWorldModelTest#returnsTitleFromResource

Surefire writes a report for each class under core/target/surefire-reports. When a test fails, read the first line of the stack trace that points to your code, not to the framework. A failure such as expected: <Home> but was: <Hello World> means the model fell back to its default title. The model did not find jcr:title, usually because the test wrote the property under a different name (for example title) or at a different path from the one the model adapts from.

[ERROR] Failures:
[ERROR]   HelloWorldModelTest.returnsTitleFromResource:23 expected: &lt;Home> but was: &lt;Hello World>
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0

Step 7: Measure coverage with JaCoCo

The archetype does not add a coverage plugin, so you add one to core/pom.xml. JaCoCo instruments the classes while the tests run and writes an HTML report. The prepare-agent goal must run before the tests, which is why it is in its own execution. Use JaCoCo 0.8.14 or later if you build with Java 25. Older versions cannot read Java 25 class files.

<!-- core/pom.xml (inside <build><plugins>) -->
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.14</version>
  <executions>
    <execution>
      <id>prepare-agent</id>
      <goals><goal>prepare-agent</goal></goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals><goal>report</goal></goals>
    </execution>
  </executions>
</plugin>
mvn -pl core clean verify
open core/target/site/jacoco/index.html   # macOS; use start on Windows or xdg-open on Linux

Open the report and check the classes with the lowest coverage. Then look for branches that are never taken. In getTitle(), the Step 3 tests cover a title and a missing title, but no test passes a title that is only spaces, so one of four branches is still red. Add a test for each gap like this, rather than chasing a total percentage.

Unit tests vs integration tests

The archetype contains both unit tests in core and integration tests in it.tests. They answer different questions, so keep both.

AspectUnit tests (core, AEM Mocks)Integration tests (it.tests)
Runs againstIn-memory mock of AEM and SlingA running AEM instance
SpeedSecondsMinutes, depending on the instance
CoversModel logic, service logic, servlet outputReal JCR, real OSGi bundles, real requests
Run withmvn -pl core testmvn clean verify -Plocal in it.tests, against a running local instance
Counts toward Cloud Manager coverageYes, measured during the build stepNo. Cloud Manager runs them as custom functional tests after deployment.

Common mistakes and troubleshooting

SymptomLikely causeFix
Model returns null in the testResource not created at the path the model reads, or the model package was not registeredCreate the resource with context.create() and call addModelsForPackage in afterSetUp
NoClassDefFoundError for AemContextAEM Mocks dependency missing or not in test scopeCheck the io.wcm.testing.aem-mock.junit5 dependency in core/pom.xml
Service is not found by getServiceService not registered before the lookupCall registerInjectActivateService first, then getService
Servlet output is emptyRequest resource or method not set before calling the servletSet the resource and method on context.request() before doGet
JaCoCo report shows 0 percentprepare-agent not run, or tests skippedRun mvn -pl core clean verify and check the execution ids
NoScrMetadataException: No OSGi SCR metadata found, when you run a test from the IDEThe IDE compiled the class, but bnd did not write the OSGI-INF metadata to target/classesRun mvn -pl core test once, or set the IDE to build and run tests with Maven
Test passes, but the value from an OSGi configuration is ignoredProperty name written with an underscore instead of a dotPass fallback.name for the element fallback_name()
Unsupported class file major version during the JaCoCo or Surefire runJaCoCo version is older than the JDK that compiled the classesUse JaCoCo 0.8.14 or later for Java 25, and the same JDK locally as in .cloudmanager/java-version

Hands-on challenge

Write a test for a page that has no jcr:title. Today, SimpleServlet prints Title = null. Decide that it should print the page name instead, for example Title = en, write the test first, watch it fail, then change the servlet. Success means all test classes pass, the JaCoCo report shows no red branches in HelloWorldModel and SimpleServlet, and no test depends on another test’s data.

Optional, if you finished Lesson 09: test SiteSettingsModel with the Context-Aware Configuration mock plugin, which AppAemContext already loads. This starting point checks one value:

    @Test
    void readsItemsPerPageFromConf() {
        MockContextAwareConfig.registerAnnotationClasses(context, SiteSettings.class);
        context.create().resource("/content/mysite", "sling:configRef", "/conf/mysite");
        MockContextAwareConfig.writeConfiguration(context, "/content/mysite",
            SiteSettings.class.getName(), "itemsPerPage", 6);

        SiteSettingsModel model = context.resourceResolver().getResource("/content/mysite")
            .adaptTo(SiteSettingsModel.class);
        assertEquals(6, model.getItemsPerPage());
    }

Add a second test for a page outside any context root, and assert the defaults: an empty analytics ID, 12 items per page and the newsletter turned off.

Key takeaways

  • Use JUnit 5 with the AEM Mocks JUnit 5 extension to test models, services and servlets without an AEM instance.
  • Keep the plugin setup in one shared helper, so every test class gets the same context.
  • Test each branch of the model, especially the defaults, because that is where production bugs hide.
  • Read the first project line of a stack trace, not the framework lines.
  • Measure coverage with JaCoCo locally. Cloud Manager treats coverage below 50% as an Important failure, and it counts conditions as well as lines.
  • Pin the JaCoCo version in your POM. Cloud Manager runs prepare-agent itself, but it does not pin a version for you.

Knowledge check

1. Which class does the JUnit 5 extension of AEM Mocks give your test?

An AemContext, created through AemContextBuilder, and injected with @ExtendWith(AemContextExtension.class).

2. Why do you call registerInjectActivateService before getService?

Because the service must be registered in the mock OSGi container before it can be looked up. The call also runs the activate method.

3. What does the prepare-agent goal of JaCoCo do?

It attaches the JaCoCo agent to the test JVM so that class coverage is recorded while the tests run.

4. What is the main difference between a unit test in core and a test in it.tests?

A unit test runs against an in-memory AEM Mocks context, while an integration test runs against a real AEM instance.

5. Every line of HelloWorldModel runs in your tests. Why can Cloud Manager still count it as partly uncovered?

Because Cloud Manager’s coverage formula counts conditions as well as lines. Each condition must evaluate to both true and false. A title that is only spaces is the case that the first two tests miss.

Frequently asked questions

Do I need a running AEM instance to run these tests?
No. AEM Mocks runs the tests in memory, so you can run them on a laptop or in a pipeline without an instance.

Why use AppAemContext instead of a new AemContext in each class?
It keeps the plugin and model setup in one place. When you add a plugin, you change one file rather than every test.

Can I mock the external API client with Mockito?
Yes. Mock only dependencies outside your bundle, and register the mock with the context before you register the service that uses it:

ExternalApiClient client = mock(ExternalApiClient.class);
when(client.fetchDisplayName("42")).thenReturn("Ankur");
context.registerService(ExternalApiClient.class, client);
context.registerInjectActivateService(new ProfileServiceImpl());

Can I still use JUnit 4?
AEM Mocks has a JUnit 4 module, io.wcm.testing.aem-mock.junit4, with an AemContext rule. The archetype uses JUnit 5, so write new tests with JUnit 5. To keep old JUnit 4 tests running during a migration, add the JUnit Vintage engine.

My code runs a JCR query. Can I unit test it?
Yes, with ResourceResolverType.JCR_OAK and the sling-mock-oak test dependency. The tests are slower, so use that type only in the test classes that need queries.

Why does my test pass on my laptop but fail in the pipeline?
Check for tests that depend on the order of execution, on local files or on the system clock. Keep each test independent, and set the data it needs in the test itself.

Is 100 percent coverage a goal?
No. Aim to cover the branches that matter, such as defaults, error paths and conditions. A high percentage with weak assertions gives false confidence.

Continue your learning

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.