AEM Unit Test Case for Sling Delegation Pattern
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.
Second, Write unit tests for the implemented model class
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).
Now Write Unit Test
Another Json file page.json (https://gist.githubusercontent.com/SadyRifat/5f11a7b58a801e1957b151e209926df9/raw/97f6510e48964f500f004224f2c25f62c34f1e77/page.json)
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.