wants to cover 100% junits on below model class, Any reference code ? | Community
Skip to main content
keshava219
Level 3
March 4, 2024
Solved

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

  • March 4, 2024
  • 3 replies
  • 877 views
@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class PageModel {
 
@586265
private Page currentPage;
 
@586265
private ValueMap properties;
 
@586265
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
* @90521 propertyName
* @90521 isMulti
* @2007960
*/
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
* @90521 resourceResolver
* @90521 tagPath
* @2007960
*/
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);
}
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 MayurSatav

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

3 replies

MayurSatav
Community Advisor and Adobe Champion
MayurSatavCommunity Advisor and Adobe ChampionAccepted solution
Community Advisor and Adobe Champion
March 4, 2024

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

arunpatidar
Community Advisor
Community Advisor
March 4, 2024

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)); } @2785667 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 @2785667 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); } @2785667 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
EstebanBustamante
Community Advisor and Adobe Champion
Community Advisor and Adobe Champion
March 4, 2024

 

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-aem-cloud/m-p/588147

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

 

Hope this helps

Esteban Bustamante