How to Unit Test Page Locale in Sling Model | Community
Skip to main content
Level 2
February 11, 2020
Solved

How to Unit Test Page Locale in Sling Model

  • February 11, 2020
  • 2 replies
  • 2213 views

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 @586265, 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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by joerghoh

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.

2 replies

BrianKasingli
Community Advisor and Adobe Champion
Community Advisor and Adobe Champion
February 11, 2020

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

 

joerghoh
Adobe Employee
joerghohAdobe EmployeeAccepted solution
Adobe Employee
February 12, 2020

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.