AEM Unit Testing with Apache Sling

Posted in AEM Tutorials By Raj On July 7, 2017


In this article, I am going to explain how to do the apache sling testing using AEM Context JUnit rule for easy access to all AEM context objects and registering adapter factories and OSGi services, before proceeding to the next, just question yourself that how much time you are spending to mock sling resource objects, how much struggle are you facing to get 80 to 90% of code coverage and the most important thing is do you really think that you are testing against to the real data ? if you ever felt like whatever I felt then you are in the right place

Personally, I don’t like to mock object by passing dummy data, I always prefer to test against to the page content. but, it is tough to test against our AEM environment instead of that I prefer to use context.loader to load page content as a JSON format and test against it, but how can I get JSON data simple you can get it by exporting page content using .infinity.json extension

As part of this example, I did not take complex example I am just using simple logic which reads child nodes of multifield and returns a list collection object, you can check sample code below

I am going to test above class by writing JUnit’s, the first approach which I am going to take here is creating JUnit using PowerMock and passing dummy data to test the list collection with this approach we need to mock every line, I feel that everyone who reads this article have basic knowledge on JUnit so, I am not going to explain what is JUnit and how to write it etc…

Code Coverage

After running mvn clean cobertura:cobertura I see code coverage is 87%, please check below screenshot


Using AEM Context

I am going to write another method which uses AEM Context here, I am not using Apache Sling Context instead of that I am using AEMContext, why I prefer this over sling context is it is an extension of sling context and also it supports most of the AEM API’s such as Page, PageManager, Tag, TagManager etc…

The first thing which I am going to do is loading JSON file as a resource, here I am using below JSON which is exported using .infinity.json extension by appending to the page

You can store JSON file in the resource folder which is under src/test/resources/listcollection folder and load it using context.load.json by passing JSON file path

If you see above code, the code is very clean and you don’t need to mock every line and the main thing is it executes against to the JSON object which is almost replica of your page and the final code is looks like below

AEMContext Code Coverage

After running mvn clean cobertura:cobertura I see code coverage is 86%, please check below screenshot