AEM Unit Test Case for Sling Delegation Pattern

Sady Rifat
2 min readMay 12, 2023

--

In Adobe Experience Manager (AEM), a Sling Model is a Java class representing a resource in the AEM content repository. Sling Models provide a convenient way to map properties of a resource to fields or methods in the Java class, allowing you to easily access and manipulate the content of the help.

We can use the JUnit framework to write a unit test for a Sling Model class in AEM. In this article, I am going to describe the way to write the Sling model class, especially for the Sling Delegation Pattern.

Step 1:

Add the necessary dependencies, annotate with AemContextExtension, and create AemContext.

AemContextExtension.@ExtendWith({AemContextExtension.class, MockitoExtension.class})
class MyCmpImplTest{
private final AemContext context = new AemContextBuilder(ResourceResolverType.JCR_MOCK).plugin(CORE_COMPONENTS).build();
}

Step 2:

  • Create a component JSON and load via context.load()
  • Attach this resource with the context current resource
  • Then adapt to your class with context.request()

Step 3:

Write your unit test.

Reality:

Following these theoretical steps and writing unit tests for Sling Delegation Pattern is not that simple. Yes, it's not that much difficult or complex, we just need to follow some tricks to make it simple.
To make it easier for developers I am giving some examples for easy understanding.

Code Example:

Breadcrumb Component:

First, create your own class to extend the core functionality.

Create an Interface that extends from the core component
Implement the Interface and build your custom logic here

Second, Write unit tests for the implemented model class

Create a JSON file of the breadcrumb component and put it under the resources folder
Be careful and double look at the init() function
This is the copy-paste code from the AEM core to enable the data layer. https://github.com/adobe/aem-core-wcm-components/blob/main/bundles/core/src/test/java/com/adobe/cq/wcm/core/components/Utils.java

Seems, do I give a simple example? Now let’s make it complicated. Take another component and customized where multifield and list exist.

Language Navigation Component:

Let’s take the Language Navigation component. My custom implementation will be will filter the core list(exclude path).

Extended Interface
My model class

Now Write Unit Test

Component Json File

Another Json file page.json (https://gist.githubusercontent.com/SadyRifat/5f11a7b58a801e1957b151e209926df9/raw/97f6510e48964f500f004224f2c25f62c34f1e77/page.json)

No need to explain this code.

Note: Writing unit test of model class the most difficult part is providing the proper json/resource. Once it is setup other things are very easy and smooth going.

--

--

Responses (1)