Hi Fellow AEM Developers,
I'm writing unit test for the SlingModel for a project that uses AEM 6.1. Sling model check if the Page has a Tag or not in the Post construct method. During the test mocked a Page with json which contains the "cq:tags" property, however the mocked page returns 0 tags when page.getTags() called.
Here are the code snippets.
SlingModel
--------------
@Model(adaptables = SlingHttpServletRequest.class)
public class SomeModel {
@Inject
@Source("sling-object")
private ResourceResolver resourceResolver;
@PostConstruct
public void postConstruct() {
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
Page page = pageManager.getPage("/content/newssite/en/category");
boolean hasTag = isPageHasTag(page);
}
public static boolean isPageHasTag(Page page) {
Tag[] tags = page.getTags();
for(Tag tag : tags) {
if(tag.getTagID().equals("news-site:news-types/sports")) {
return true;
}
}
return false;
}
}
Now i have to call this is in postConstruct() since the actual logic is lot more than this.
Page JSON
------------
{
"jcr:primaryType": "cq:Page",
"jcr:content": {
"jcr:primaryType": "nt:unstructured",
"jcr:title": "News",
"imagePath": "/content/dam/news-site/image.png",
"hideInNav": "false",
"cq:tags": ["news-site:news-types/sports"],
"sling:resourceType": "newssite/components/structure/generic-page"
}
}
tried with
cq:tags": "[news-site:news-types/sports]" as well
Test Code
-------------
@RunWith(PowerMockRunner.class)
public class TopNavControllerTest {
@Rule
public AemContext context = new AemContext();
@Before
public void setup() throws Exception {
context.load().json("/test/category_page.json", "/content/newssite/en/category");
Resource categoryPageResource = context.resourceResolver().getResource("/content/newssite/en/category");
context.request().setResource(categoryPageResource);
}
@Test
public void testPostConstruct() {
//This should call postConstruct() and check Tag
SomeModel someModel = context.request().adaptTo(SomeModel.class);
//Assert
}
}
Dependnecy
---------------
<dependency>
<groupId>io.wcm</groupId>
<artifactId>io.wcm.testing.aem-mock</artifactId>
<version>1.9.8</version>
<scope>test</scope>
</dependency>
I'm not sure what's wrong.
Any help is much appreciated.
Thanks so much in Advance.