How to Unit Test Sling Models using JUnit 5 and AemContext?

It is very easy to unit test sling models using the latest JUnit 5 and AemContext class. If you think you don’t need to write unit tests as a developer, check out our blog on JUnits: Why It Is Important For A Developer To Write Unit Testsonce you are convinced with the message of the blog, let us learn a little bit about the AemContext first to proceed.

What is AemContext?

AemContext is a class from the wcm.io AEM Mocks library used in JUnit 5 tests to facilitate the creation and manipulation of a mock AEM environment for unit testing your Sling Models and other AEM-specific components. Here’s a quick overview:

Benefit of AemContext

  • Provides a mock AEM environment within your JUnit 5 tests.
  • Allows you to test Sling Models and other AEM components without requiring a running AEM instance.
  • Offers convenient methods to configure the mock environment, inject mock data, and access mock objects like resources and requests.
why developer should do unit testing

See it in Action

Sample Sling Model

@Model(adaptables = Resource.class)
public class SampleModel {

    @Inject
    @Named("title")
    private String title;

    public String getTitle() {
        return title;
    }
}

Corresponding JUnit 5 Test

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import io.wcm.testing.mock.aem.junit5.AemContext;

import static org.junit.jupiter.api.Assertions.*;

public class SampleModelTest {

    private final AemContext context = new AemContext();

    @BeforeEach
    public void setUp() {
        context.registerInjectAdapter(ValueMap.class, MockValueMap.class);
        context.load().json("/content/mypage.json", "/content");
    }

    @Test
    public void testModelGetsTitle() {
        SampleModel model = context.request().adaptTo(SampleModel.class);
        assertNotNull(model);
        assertEquals("Sample Title", model.getTitle());
    }
}

Sample mypage.json

{
  "jcr:primaryType": "nt:unstructured",
  "title": "Sample Title",
  "description": "This is a sample page for testing purposes."
}

Once you include the above test code in your code base, it will always make sure that any other developer does not change your sling model by mistake e.g. the title is changed to titleText or may delete the field without ensuring its impact. Also, it makes sure about the behavior this sling model brings in your code base e.g. in other services or servlets.

These unit tests are easy and fun to write. Once you start securing and covering your code with good unit tests, you will be confident about your code in higher environments. 🙂

Hope you liked this simple explanation. Feel free to share your thoughts/doubts in the comments section below.

Further Readings

Spread the word!
0Shares

Leave a comment

Your email address will not be published. Required fields are marked *