Expand my Community achievements bar.

SOLVED

wants to cover 100% junits on below model class, Any reference code ?

Avatar

Level 4
@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class PageModel {
 
private Page currentPage;
 
private ValueMap properties;
 
private InheritanceValueMap pageProperties;
 
private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
/**
* method to fetch page properties data of each tag and to return the tag titles
* @Param propertyName
* @Param isMulti
*/
public String getTagTitles(String propertyName, boolean isMulti, boolean isInherited) {
String tagTitle = null;
String tagPath = null;
String businessTagPath = null;
Value[] values = null;
try {
logger.debug("Inside getTagTitles: {}", currentPage);
ResourceResolver resourceResolver = currentPage.getContentResource().getResourceResolver();
if (isMulti) {
logger.debug("Inside getTagTitles multi tag property: {}", propertyName);
if (isInherited) {
values = null != pageProperties ? pageProperties.getInherited(propertyName, Value[].class) : null;
} else {
values = null != properties ? properties.get(propertyName, Value[].class) : null;
}
StringBuffer tagBuffer = new StringBuffer();
if (values != null) {
for (Value typeTagId : values) {
tagPath = typeTagId.getString();
tagBuffer.append(getTagTitle(resourceResolver, tagPath) + ";");
}
if (tagBuffer.length() != 0)
tagBuffer.deleteCharAt(tagBuffer.length() - 1);
}
tagTitle = tagBuffer.toString();
} else {
logger.debug("Inside getTagTitles single tag property: {}", propertyName);
if (isInherited) {
if (StringUtils.equalsIgnoreCase(propertyName, "cq:division")) {
if (StringUtils.isNotEmpty(properties.get("cq:businessArea", null))) {
tagPath = null != properties ? properties.get(propertyName, null) : null;
businessTagPath = null != properties ? properties.get("cq:businessArea", null) : null;
} else {
tagPath = null != pageProperties ? pageProperties.getInherited(propertyName, null) : null;
businessTagPath = null != pageProperties
? pageProperties.getInherited("cq:businessArea", null)
: null;
}
if (null != tagPath && !tagPath.startsWith(businessTagPath)) {
return null;
}
} else {
tagPath = null != pageProperties ? pageProperties.getInherited(propertyName, null) : null;
}
} else {
tagPath = null != properties ? properties.get(propertyName, null) : null;
}
tagTitle = getTagTitle(resourceResolver, tagPath);
}
} catch (RepositoryException e) {
logger.error("Error in getting tag title:  {}", e);
}
logger.debug("Inside getTagTitles tag title before return: {}", tagTitle);
return tagTitle;
}
 
/**
* Method to get title from tag manager
* @Param resourceResolver
* @Param tagPath
*/
private static String getTagTitle(ResourceResolver resourceResolver, String tagPath) {
String tagTitle = null;
TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
Tag resolve = Objects.requireNonNull(tagManager).resolve(tagPath);
if (null != resolve)
tagTitle = resolve.getTitle();
return tagTitle;
}
 
public String getContentLanguage() {
return getTagTitles("cq:contentLang", false, false);
}
 
public String getCountry() {
return getTagTitles("cq:country", true, true);
}
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @keshava219 ,

I hope this reference snippet will work.

@Before
    public void setUp() throws RepositoryException {
        when(request.getResource()).thenReturn(resource);
        when(resource.getResourceResolver()).thenReturn(resourceResolver);
        when(resourceResolver.adaptTo(TagManager.class)).thenReturn(tagManager);
        when(tagManager.resolve("sampleTagPath")).thenReturn(tag);
        when(tag.getTitle()).thenReturn("Sample Tag Title");
        
        // Mocking ValueMap
        Map<String, Object> map = new HashMap<>();
        map.put("cq:division", "sampleTagPath");
        map.put("cq:businessArea", "sampleBusinessTagPath");
        when(properties.get("cq:division", String.class)).thenReturn("sampleTagPath");
        when(properties.get("cq:businessArea", String.class)).thenReturn("sampleBusinessTagPath");
        
        pageModel = new PageModel();
        pageModel.currentPage = resource.adaptTo(com.day.cq.wcm.api.Page.class);
        pageModel.properties = properties;
        pageModel.pageProperties = mock(com.day.cq.wcm.api.Page.class).adaptTo(ValueMap.class);
    }

    @Test
    public void testGetContentLanguage() {
        String contentLang = pageModel.getContentLanguage();
        assertEquals("Sample Tag Title", contentLang);
    }

 I have add one sample test case for getContentLanguage() method

View solution in original post

3 Replies

Avatar

Correct answer by
Community Advisor

Hi @keshava219 ,

I hope this reference snippet will work.

@Before
    public void setUp() throws RepositoryException {
        when(request.getResource()).thenReturn(resource);
        when(resource.getResourceResolver()).thenReturn(resourceResolver);
        when(resourceResolver.adaptTo(TagManager.class)).thenReturn(tagManager);
        when(tagManager.resolve("sampleTagPath")).thenReturn(tag);
        when(tag.getTitle()).thenReturn("Sample Tag Title");
        
        // Mocking ValueMap
        Map<String, Object> map = new HashMap<>();
        map.put("cq:division", "sampleTagPath");
        map.put("cq:businessArea", "sampleBusinessTagPath");
        when(properties.get("cq:division", String.class)).thenReturn("sampleTagPath");
        when(properties.get("cq:businessArea", String.class)).thenReturn("sampleBusinessTagPath");
        
        pageModel = new PageModel();
        pageModel.currentPage = resource.adaptTo(com.day.cq.wcm.api.Page.class);
        pageModel.properties = properties;
        pageModel.pageProperties = mock(com.day.cq.wcm.api.Page.class).adaptTo(ValueMap.class);
    }

    @Test
    public void testGetContentLanguage() {
        String contentLang = pageModel.getContentLanguage();
        assertEquals("Sample Tag Title", contentLang);
    }

 I have add one sample test case for getContentLanguage() method

Avatar

Community Advisor

To achieve 100% code coverage in your JUnit test case, you'll need to create test scenarios that cover various branches(if else), conditions, and methods in your PageModel class. Here's a basic example of a JUnit test case using the Mockito framework to mock the necessary dependencies:

 

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

import java.util.HashMap;
import java.util.Map;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class PageModelTest {

    @Mock
    private Page currentPage;

    @Mock
    private ValueMap properties;

    @Mock
    private InheritanceValueMap pageProperties;

    @Mock
    private SlingHttpServletRequest slingHttpServletRequest;

    @InjectMocks
    private PageModel pageModel;

    @Before
    public void setUp() {
        when(currentPage.getContentResource()).thenReturn(mock(Resource.class));
        when(currentPage.getContentResource().getResourceResolver()).thenReturn(mock(ResourceResolver.class));
    }

    @test
    public void testGetTagTitlesMultiTagInherited() {
        // Mocking values for properties.get(propertyName, Value[].class)
        Value[] values = new Value[]{mock(Value.class)};
        when(pageProperties.getInherited("propertyName", Value[].class)).thenReturn(values);

        // Mocking the getTagTitle method
        when(pageModel.getTagTitle(any(ResourceResolver.class), anyString())).thenReturn("MockedTagTitle");

        // Test the method
        String result = pageModel.getTagTitles("propertyName", true, true);

        // Assert the result
        assertEquals("MockedTagTitle", result);
    }

    // Add more test cases for different scenarios and methods

    @test
    public void testGetContentLanguage() {
        // Mocking the getTagTitles method
        when(pageModel.getTagTitles("cq:contentLang", false, false)).thenReturn("MockedContentLanguage");

        // Test the method
        String result = pageModel.getContentLanguage();

        // Assert the result
        assertEquals("MockedContentLanguage", result);
    }

    @test
    public void testGetCountry() {
        // Mocking the getTagTitles method
        when(pageModel.getTagTitles("cq:country", true, true)).thenReturn("MockedCountry");

        // Test the method
        String result = pageModel.getCountry();

        // Assert the result
        assertEquals("MockedCountry", result);
    }
}

 

This is a basic example, and you may need to customize it based on your specific use cases. Ensure that you cover various conditions and edge cases in your test cases to achieve comprehensive code coverage.

 



Arun Patidar

Avatar

Community Advisor

 

In addition to @arunpatidar and @MayurSatav responses, I think the most important thing to understand is that achieving 100% coverage is not always useful, as it often includes covering default behaviors such as testing "getter" and "setter" methods. However, if you truly need to achieve a 100% score, you just need to use the Jacoco plugin to see the percentage of coverage you currently have, then build new test classes and recheck until you reach 100%.

 

You can check out these articles on how to set up and check your code coverage percentage

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/check-junit-coverage-on-ae...

https://medium.com/@karlrombauts/setting-up-unit-testing-for-java-in-vs-code-with-maven-3dc75579122f

 

Hope this helps



Esteban Bustamante