How to Unit Test Page Locale in Sling Model




    I am creating a component that requires the Page Locale to make decisions on what to display. I am able to get the Page object using @inject, but i am not sure how to Unit Test this models now. I tried creating an entire structure in unit tests json and passed it to AEMContent.currentResource() but that doesn't inject the Page object. 

    Any help would be appreciated.




Accepted Solutions (1)

Accepted Solutions (1)




i would create a spy for the injected page and mock the getLocale() API call. In the end you are not interested in how the locale is calculated, but just in the result of it.

Answers (1)

Answers (1)




Hello, @rajdevms,


If you are writing Java unit test utilising the JUnit4 library. Then you can use the AEM Mocks library where it can easily enable you to test your sling models. Utilising the AEM Mocks Library, when you initiate a resource in memory, the properties can be obtained in the Sling Annotation of @Inject.



// Sling Model
@Model(adaptables = Resource.class)
public class CustomComponent {

    // @ValueMapValue; another way to obtain the page's property value.
    private String myCustomComponentPropertyKey;

    private String myLang;

    public void init() {
        myLang = myCustomComponentPropertyKey + "hello";

    public String getMyLang() {
        return myLang;

// JUnit4 Sling Model Unit Test
public class CustomComponentTest {

    public final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);

    private CustomComponent underTest;

    public void itShouldReturnTheCorrectCustomisedPropertyValue() {
        Resource myPage = context.create().resource("/content/mysite/en/home", new ValueMapDecorator(ImmutableMap.<String, Object> of(
            "myCustomComponentPropertyKey", "en",
            "anotherProperty", "example")));

        underTest = myPage.adaptTo(CustomComponent.class);
        assertEquals("enhello", underTest.getMyLang());


To set up your project for JUnit 4, you can refer to this blog, as that's where I found some examples for the code provided above.