Objective

  1. Understand the basics of unit testing.
  2. Learn about frameworks and tools commonly used to test AEM code.
  3. Understand options for mocking or simulating AEM resources when writing unit tests.

Background

In this tutorial, we’ll explore how to write Unit Tests for our Byline component’s Sling Model (created in the Creating a custom AEM Component). Unit tests are build-time tests written in Java™ that verify expected behavior of Java™ code. Each unit test is typically small, and validates the output of a method (or units of work) against expected results.

We use AEM best practices, and employ:

Unit Testing and Adobe Cloud Manager

Adobe Cloud Manager integrates unit test execution and code coverage reporting into its CI/CD pipeline to help encourage and promote the best practice of unit testing AEM code.

While unit testing code is a good practice for any code base, when using Cloud Manager it is important to take advantage of its code quality testing and reporting facilities by providing unit tests for Cloud Manager to run.

Update the test Maven dependencies

The first step is to inspect Maven dependencies to support writing and running the tests. There are four dependencies required:

  1. JUnit5
  2. Mockito Test Framework
  3. Apache Sling Mocks
  4. AEM Mocks Test Framework (by io.wcm)

The JUnit5, **Mockito, and AEM Mocks test dependencies are automatically added to the project during setup using the AEM Maven archetype.

  1. To view these dependencies, open the Parent Reactor POM at aem-guides-wknd/pom.xml, navigate to the <dependencies>..</dependencies> and view the dependencies for JUnit, Mockito, Apache Sling Mocks, and AEM Mock Tests by io.wcm under <!-- Testing -->.

  2. Ensure that io.wcm.testing.aem-mock.junit5 is set to 4.1.0:

    <dependency>
        <groupId>io.wcm</groupId>
        <artifactId>io.wcm.testing.aem-mock.junit5</artifactId>
        <version>4.1.0</version>
        <scope>test</scope>
    </dependency>
    
    CAUTION
    Archetype 35 generates the project with io.wcm.testing.aem-mock.junit5 version 4.1.8. Please downgrade to 4.1.0 to follow the rest of this chapter.
  3. Open aem-guides-wknd/core/pom.xml and view that the corresponding testing dependencies are available.

    A parallel source folder in the core project will contain the unit tests and any supporting test files. This test folder provides separation of test classes from the source code but allows the tests to act as if they live in the same packages as the source code.