Expand my Community achievements bar.

SOLVED

How to Unit Test Page Locale in Sling Model

Avatar

Level 2

Hi,

    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.

 

Thanks,

Raj

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

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.

View solution in original post

2 Replies

Avatar

Community Advisor

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.

 

Example:

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

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

    private String myLang;

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

    public String getMyLang() {
        return myLang;
    }
}

// JUnit4 Sling Model Unit Test
@RunWith(MockitoJUnitRunner.class)
public class CustomComponentTest {

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

    private CustomComponent underTest;

    @Test
    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. https://sourcedcode.com/aem-sling-models-unit-test-junit-4-with-examples

 

Avatar

Correct answer by
Employee Advisor

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.