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