It’s difficult to imagine a modern software application that can live without JUnit tests. In a previous article on JUnit testing, JUnit Tests for WCMUsePojo Objects, we included a tip involving a project we were working on. For this article, we use the same project and extend the approach with sling models and a direct connection to a real AEM repository.

In our case, we encountered a problem when we had to test a big back-end service that had a lot of dependencies with other services, data, and web content inside a JCR repository. Creating JUnit tests for AEM components and services requires preparing tons of data, so we implemented a solution that helps save time in preparing all of this data. We were able to use a real repository and data prepared in AEM using all of AEM’s capabilities. This solution significantly sped up writing tests and improved the quality of tests.

Connecting a JUnit test to AEM is a no-brainer requiring just a few simple steps:

  1. Download a class package https://github.com/apache/sling-org-apache-sling-testing-sling-mock-oak/tree/master/src/main/java/org/apache/sling/testing/mock/sling/oak
  2. Include the WEB DAV repository factory org.apache.jackrabbit:jackrabbit-jcr2dav dependency in your pom.xml file
  3. Modify the OakMockSlingRepository class from the first step to use the ProxyRepository Connection. Here’s just the changed code:

Now you can declare an AemContext Test Rule in your test cases:

It will use your AEM Repository for tests. Almost anything is possible now, just use a real repository path and adapt to page or sling model:

Tips for Additions

Here is a list of nice tips for additions to your tests’ base class that can help you with complex tests:

OSGi configs for the test context 

Run modes for the test context 

Add package with models (useful examples for ACS lists)

Inject and Activate services (any of your real services or external services like GenericListAdapterFactory)

Register any AEM Mock Service without activation, just to satisfy dependencies

Supply the context and sling models with sling request related objects

How can we help you?
Contact Us