Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
BedrockMission!

Learn More

View all

Sign in to view all badges

AemMock in JUnit4 is not able to return page.getTemplate

Avatar

Avatar
Ignite 1
Level 1
RRaj
Level 1

Likes

0 likes

Total Posts

2 posts

Correct Reply

0 solutions
Top badges earned
Ignite 1
View profile

Avatar
Ignite 1
Level 1
RRaj
Level 1

Likes

0 likes

Total Posts

2 posts

Correct Reply

0 solutions
Top badges earned
Ignite 1
View profile
RRaj
Level 1

26-10-2020

I am trying to run the test for one of my Model class for Custom Render Condition. Its testing if current is a template allowed to show the tab/field in dialog. When I am running test for this code using AemMock and JUnit4 its failing when debug I found its not able to get template from the page object: 

 

            final Template pageTemplate = page.getTemplate();
//The above, getTemplate returns null for my Unit test below
            templatePathOfCurrentPage = pageTemplate.getName();

 

But at the same time if I change the code for getting the template with Resource API it works perfectly fine:

 

            Resource pageResource = page.getContentResource();
            templatePathOfCurrentPage = pageResource.getValueMap().get("cq:template", String.class);

 

Any pointer on this or suggestion to solve this will highly appreciated.

 

This is my Unit test:

 

package com.abc.models;

import com.adobe.cq.sightly.WCMBindings;
import com.adobe.granite.ui.components.rendercondition.RenderCondition;
import com.adobe.granite.ui.components.rendercondition.SimpleRenderCondition;
import com.abc.AppAemContext;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.WCMException;
import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.models.factory.ModelFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertFalse;

@RunWith(MockitoJUnitRunner.class)
public class TemplateTypeRenderConditionTest {

    private static final String DEST_ROOT = "/content/sample/abc";
    private static final String TEMPLATE_PATH = "/conf/abc/settings/wcm/templates/homepage";
    private static final String PAGE_ROOT = "/content/sample/abc/index";

    
    public final AemContext CONTEXT = AppAemContext.newAemContext();

    @Mock
    PageManager pageManager;

    SlingHttpServletRequest request;
    SlingBindings slingBindings;


    @Before
    public void setUp() throws NoSuchFieldException, WCMException {

        slingBindings = (SlingBindings) CONTEXT.request().getAttribute(SlingBindings.class.getName());
        slingBindings.put(WCMBindings.PAGE_MANAGER, pageManager);
        slingBindings.put(SlingBindings.RESOURCE, CONTEXT.resourceResolver().getResource(DEST_ROOT));

        // prepare sling request
        CONTEXT.request().setAttribute(SlingBindings.class.getName(), slingBindings);
        CONTEXT.request().setResource(CONTEXT.resourceResolver().getResource(DEST_ROOT));
        CONTEXT.pageManager().create(DEST_ROOT, "index", TEMPLATE_PATH, "title1");
    }
    
    public void itShouldReturnTheResourceMatchesTheTemplateTypeFromItemParamter() throws WCMException {
        CONTEXT.request().setQueryString("item="+PAGE_ROOT);
        CONTEXT.getService(ModelFactory.class).createModel(CONTEXT.request(), TemplateTypeRenderCondition.class);
        final SimpleRenderCondition resultingRenderCond = (SimpleRenderCondition)  CONTEXT.request().getAttribute(RenderCondition.class.getName());

        assert(resultingRenderCond.check());
    }
}

 

Apps AEM Context setup:

 

package com.abc.models;

import com.adobe.acs.commons.models.injectors.impl.AemObjectInjector;
import com.abc.models.TemplateTypeRenderCondition;
import io.wcm.testing.mock.aem.MockAemAdapterFactory;
import io.wcm.testing.mock.aem.junit.AemContext;
import io.wcm.testing.mock.aem.junit.AemContextCallback;
import org.apache.sling.api.adapter.AdapterFactory;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import java.io.IOException;

public class AppAemContext {
    private static final String DEST_ROOT = "/content/sample/abc";
    private static final String TEST_JSON = "/templatetyperendercondition/test-content.json";
    public static AemContext newAemContext() {
        return new AemContext(new SetUpCallback(), ResourceResolverType.JCR_MOCK);
    }

    private static final class SetUpCallback implements AemContextCallback {

        
        public void execute(AemContext context) throws PersistenceException, IOException {
            // application-specific services for unit tests
            context.registerService(AdapterFactory.class, new MockAemAdapterFactory());
            context.registerService(new AemObjectInjector());

            // register models from package
            context.addModelsForPackage("com.abc.models");
            context.load().json(TEST_JSON, DEST_ROOT);
        }
    }
}

 

 

This is my class and test fixture for PoM  below:

 

package com.abc.models;

import com.adobe.granite.ui.components.rendercondition.RenderCondition;
import com.adobe.granite.ui.components.rendercondition.SimpleRenderCondition;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ScriptVariable;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

@Model(adaptables = SlingHttpServletRequest.class)
public class TemplateTypeRenderCondition {
    private final Logger logger = LoggerFactory.getLogger(TemplateTypeRenderCondition.class);

    
    private SlingHttpServletRequest request;

    @ScriptVariable
    private PageManager pageManager;

    @ValueMapValue
    private String[] templatePath;

    @PostConstruct
    public void init() {

        // Get the resource page path for which propery is being edited
        final String pathPage = request.getParameter("item");

        //Assign suffix as path for Create Page wizard
        final String suffix = request.getRequestPathInfo().getSuffix();;


        // Still cannot found the through exception
        if (pathPage == null && suffix == null) {
            throw new IllegalArgumentException("Could not determine page from <" + request.getPathInfo() + "> , neither suffix in create page wizard or, item in editor");
        }
        logger.info("Path Info for the page property editing from RenderCondition is {}", request.getPathInfo());
        String templatePathOfCurrentPage = null;
        if(pathPage != null) {
            final Page page = pageManager.getPage(pathPage);
            if (page == null) {
                throw new IllegalArgumentException("Resource at <" + pathPage + "> is not a page");
            }

            //final Template pageTemplate = page.getTemplate();
            Resource pageResource = page.getContentResource();
            templatePathOfCurrentPage = pageResource.getValueMap().get("cq:template", String.class);
        } else if( suffix != null){
            templatePathOfCurrentPage = suffix;
        }
        // Check if we have the template from page
        if(templatePath.length < 1) {
                throw new IllegalArgumentException("Could not get page template match from <" + request.getPathInfo() + ">");
        }
        final List<String> listTemplates = Arrays.asList(templatePath);
        final boolean show = listTemplates.contains(templatePathOfCurrentPage);
        // Add the render condition based on check if list of templatePath has current page template allowed
        request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(show));
    }
public String[] getTemplatePath(){
        return templatePath;
    }
}
		<!-- test dependencies -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>junit-addons</groupId>
			<artifactId>junit-addons</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.api</artifactId>
			<version>2.18.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.adapter</artifactId>
			<version>2.1.6</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.jcr.api</artifactId>
			<version>2.4.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.jcr.resource</artifactId>
			<version>3.0.18</version>
			<scope>test</scope>
		</dependency>
		<!-- for testing we need the new ResourceTypeBasedResourcePicker -->
	    <dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.models.impl</artifactId>
			<version>1.4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- Added for Powemock -->
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
		</dependency>

		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito-common</artifactId>
			<version>1.7.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
			<version>1.7.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-easymock</artifactId>
			<version>1.5.5</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.easymock</groupId>
			<artifactId>easymock</artifactId>
			<version>3.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.testing.osgi-mock</artifactId>
			<version>2.4.14</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.testing.jcr-mock</artifactId>
			<version>1.4.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.testing.resourceresolver-mock</artifactId>
			<version>1.1.26</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.wcm</groupId>
			<artifactId>io.wcm.sling.commons</artifactId>
			<version>1.3.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.testing.sling-mock.junit4</artifactId>
			<version>2.4.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.testing.sling-mock-oak</artifactId>
			<version>2.1.6</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.wcm</groupId>
			<artifactId>io.wcm.testing.aem-mock.junit4</artifactId>
			<version>3.0.0</version>
			<scope>test</scope>
		</dependency>

 

 

AemMock getTemplate junit page