Expand my Community achievements bar.

Applications for the 2024-2025 Adobe Experience Manager Champion Program are open!

J unit test case for pojo class

Avatar

Level 1
Hi 
I have to write test case for this class I am trying to mock all the object but not able to get the full coverage.
can anyone please help me to write the test for this class


import
org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Helper {


public static List<String> validateResortIdForVideo(List<String> metadataValidatedVideosList,
ResourceResolver resolver, PropertiesConstant vConfig) {
log.info("Enetring validateResortIdForVideo....." + metadataValidatedVideosList);

MetadataValidationHelper metadataValidationHelper = new MetadataValidationHelper();

String migrationSwitch = vConfig.getVIDEO_MIGRATIONSWITCH();// osgi interface
HashMap<String, RDVideoMetaDataVO> metaRDMap = null;

Asset asset = null;
String resortId = null;
String resortName = null;
String cityName = null;
String stateName = null;
String affiliationStatus = null;
String regionHierarchy = null;
Calendar affiliationDate = null;
String resortRentalNetwork = null;
RDVideoMetaDataVO metadataVO = null;
// VideoMoveHelper videoMoveHelper = new VideoMoveHelper();
List<String> pVideosList = new ArrayList<String>();
List<String> eVideoAssetIDList = new ArrayList<String>();
List<Asset> rVideoAssets = new ArrayList<Asset>();
for (String listItem : metadataValidatedVideosList) {
log.info(listItem + " list item ");
rVideoAssets.add(VideoWorkFlowHelper.getAssetByPath(listItem, resolver));

List<Asset> revisedRDVideoAssets = new ArrayList<Asset>();

try {
// Listing RD videos to check further and set metadata accordingly
for (int assetsCnt = 0; assetsCnt < rVideoAssets.size(); assetsCnt++) {
List<String> assetType = MetadataValidationHelper
.getCustomAssetType(rVideoAssets.get(assetsCnt), vConfig, false, resolver);
log.info("revised asset list");
if (assetType.contains(AssetType.ASSET_TYPE_RD)
|| assetType.contains(AssetType.ASSET_TYPE_RD_RCITV)) {
revisedRDVideoAssets.add(rVideoAssets.get(assetsCnt));
}
}

// Listing Resort IDs tagged with video assets

List<String> rdResortIDList = getResortIdListFromAssetList(rVideoAssets, MetadataConstant.RD_RESORTID, resolver);
List<String> tvResortIDList = getResortIdListFromAssetList(rVideoAssets, MetadataConstant.TV_RESORTID, resolver);
List<String> resortIDList = new ArrayList<String>();
resortIDList.addAll(rdResortIDList);
resortIDList.addAll(tvResortIDList);
log.info("resort-id-list" + resortIDList);

// Calling service and storing model against Resort ID List
if (null != resortIDList && !resortIDList.isEmpty()) {
metaRDMap = retrieveMetaDataFromRD(resortIDList, migrationSwitch);
}
if (null != metaRDMap) {
for (int i = 0; i < rVideoAssets.size(); i++) {
asset = rVideoAssets.get(i);
resortId = null;
List<String> assetTypeList = MetadataValidationHelper.getCustomAssetType(asset, vConfig,
false, resolver);
boolean isRDtaggedAsset = false, isRCITVtaggedAsset = false;

if (assetTypeList != null && (assetTypeList.contains(AssetType.ASSET_TYPE_RCITV)
|| assetTypeList.contains(AssetType.ASSET_TYPE_RCI_TV_PREVIEW))) {
isRCITVtaggedAsset = true;
}
if (assetTypeList != null && (assetTypeList.contains(AssetType.ASSET_TYPE_RD)
|| assetTypeList.contains(AssetType.ASSET_TYPE_RD_RCITV))) {
isRDtaggedAsset = true;
}
String rdResortId = VideoWorkFlowHelper.getMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.RD_RESORTID, String.class);
log.debug(rdResortId + "line no 99");
String tvResortId = VideoWorkFlowHelper.getMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.TV_RESORTID, String.class);
log.debug(tvResortId + "line no 104");
boolean tvResortIdFlag = false;

if (null != rdResortId && isRDtaggedAsset) {
resortId = rdResortId;
if (null != tvResortId && isRCITVtaggedAsset) {
resortId = rdResortId + "," + tvResortId;
}
log.info(resortId + "-- line 108");

} else if (null != tvResortId && isRCITVtaggedAsset) {
resortId = tvResortId;
tvResortIdFlag = true;
log.info(resortId + "-- line 113");
}
log.debug("Asset:" + asset.getName() + " is tagged to resorts having ID : " + resortId);
boolean resortMetadataFlag = false;

if (null != resortId && !resortId.isEmpty()) {
StringTokenizer resortIdToken = new StringTokenizer(resortId, ",");
for (int j = 0; resortIdToken.hasMoreTokens(); j++) {
resortId = resortIdToken.nextToken().trim();
log.info(resortId + " line 121");
boolean resortIdFlag = false;
if (null != resortId && !resortId.isEmpty()) {
metadataVO = (RDVideoMetaDataVO) metaRDMap.get(resortId.toLowerCase());
resortIdFlag = true;
}
log.debug("ResortID:" + resortId + " And its metedata: " + metadataVO);
// If video is tagged to any invalid Resort ID : store the video asset in error
// list and error map
if (metadataVO == null && resortIdFlag == true) {
log.debug("Asset:" + asset.getName() + " is not tagged to valid resort(s).");
eVideoAssetIDList.add(asset.getPath());
// ErrorMapBean.setError(asset.getName(),ErrorConstant.VIDEO_INCORRECT_RESORTID
// + resortId);
resortMetadataFlag = false;
log.info("code -- endding");
break;
} else {
log.info("--line 139");
resortMetadataFlag = true;
if (revisedRDVideoAssets.contains(asset)) { /// j==o to do
log.info("--line 142");
resortName = metadataVO.getResortName();
log.info(resortName + "141");
cityName = metadataVO.getCity();
stateName = metadataVO.getStateProvince();
affiliationStatus = metadataVO.getAffiliationStatus();
regionHierarchy = metadataVO.getRegionHierarchy();
}
}
}
log.info("resmetadflag-- " + resortMetadataFlag + " -tv resort flag- " + tvResortIdFlag
+ "=---=" + revisedRDVideoAssets.contains(asset) + "---" + asset + "-- ");
// setting required metadata if video is RD video & tagged to valid resorts only
if (resortMetadataFlag == true && revisedRDVideoAssets.contains(asset)
&& tvResortIdFlag == false) {
log.info("Entering in line no 160 in validation helper");
if (null != resortName && !resortName.isEmpty()) {
VideoWorkFlowHelper.setMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.RD_RESORTNAME, resortName);
}
if (null != cityName && !cityName.isEmpty()) {
VideoWorkFlowHelper.setMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.RD_CITY, cityName);
}


if (null != stateName && !stateName.isEmpty()) {
VideoWorkFlowHelper.setMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.RD_STATE, stateName);

}

if (null != affiliationStatus && !affiliationStatus.isEmpty()) {
VideoWorkFlowHelper.setMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.RD_AFFILIATIONSTATUS, affiliationStatus);
}

if (null != regionHierarchy && !regionHierarchy.isEmpty()) {
VideoWorkFlowHelper.setMetadataPropertyValue(resolver, asset.getPath(),
MetadataConstant.RD_REGIONHIERARCHY, regionHierarchy);

}


}
if (resortMetadataFlag == true && !eVideoAssetIDList.contains(asset.getPath())) {
log.debug(
"Asset:" + asset.getName() + " is validated against all resorts tagged to it.");
pVideosList.add(asset.getPath());
}
} else {
pVideosList.add(asset.getPath());
}
}
} else {
pVideosList = metadataValidatedVideosList;
}
if (eVideoAssetIDList != null && !eVideoAssetIDList.isEmpty()) {
log.info("list of videos moved to error Folder as " + eVideoAssetIDList);
VideoMoveHelper.moveRevisedToTarget(errorVideoAssetIDList,resolver,vConfig,(vConfig.getVIDEO_ERROR_ASSETS()));
}
}

catch (Exception e) {
log.info("Error while validating video assets against ResortID...." + e);
ErrorMapBean.setExceptionHeaderAtValidation("Error while validating video assets against ResortID....");


}

}
return pVideosList;

}

Request you to please provide the sample junits code for above example

2 Replies

Avatar

Level 7

Hi @UjjawalKu ,

To write JUnit tests for the provided Helper class, you'll need to mock certain dependencies such as ResourceResolver and PropertiesConstant. Additionally, you'll need to mock some method calls like VideoWorkFlowHelper.getAssetByPath() and retrieveMetaDataFromRD(). Here's an example of how you can write JUnit tests for this class:

 

import static org.mockito.Mockito.*;

import java.util.ArrayList;
import java.util.List;

import org.apache.sling.api.resource.ResourceResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;

@ExtendWith(MockitoExtension.class)
public class HelperTest {

    @Mock
    private ResourceResolver resolver;

    @Mock
    private PropertiesConstant vConfig;

    @Mock
    private Logger log;

    private Helper helper;

    @BeforeEach
    public void setUp() {
        helper = new Helper();
    }

    @Test
    public void testValidateResortIdForVideo() {
        // Mock necessary dependencies and method calls
        List<String> metadataValidatedVideosList = new ArrayList<>();
        metadataValidatedVideosList.add("path/to/video1");
        metadataValidatedVideosList.add("path/to/video2");

        when(vConfig.getVIDEO_MIGRATIONSWITCH()).thenReturn("migrationSwitchValue");

        // Mock the behavior of VideoWorkFlowHelper.getAssetByPath()
        Asset mockAsset1 = mock(Asset.class);
        Asset mockAsset2 = mock(Asset.class);
        when(VideoWorkFlowHelper.getAssetByPath("path/to/video1", resolver)).thenReturn(mockAsset1);
        when(VideoWorkFlowHelper.getAssetByPath("path/to/video2", resolver)).thenReturn(mockAsset2);

        // Mock the behavior of retrieveMetaDataFromRD()
        HashMap<String, RDVideoMetaDataVO> mockMetaRDMap = new HashMap<>();
        when(helper.retrieveMetaDataFromRD(anyList(), anyString())).thenReturn(mockMetaRDMap);

        // Mock other necessary method calls as needed

        // Call the method under test
        List<String> result = Helper.validateResortIdForVideo(metadataValidatedVideosList, resolver, vConfig);

        // Assert the result or verify certain behaviors
        // For example:
        // assertEquals(expectedResultSize, result.size());
        // verify(resolver, times(expectedMethodCalls)).someMethod();
    }
}

 

In this test class:

  1. We're mocking dependencies such as ResourceResolver and PropertiesConstant using Mockito's @Mock annotation.
  2. In the setUp() method, we instantiate the Helper class that we want to test.
  3. In the testValidateResortIdForVideo() method, we mock the behavior of methods like VideoWorkFlowHelper.getAssetByPath() and retrieveMetaDataFromRD() using Mockito's when().thenReturn() syntax.
  4. We then call the method under test (Helper.validateResortIdForVideo()) with the mocked parameters and verify the behavior or assert the results as needed.

You'll need to expand and customize this test class further based on your specific requirements and dependencies. Additionally, you may need to mock additional method calls and handle exceptions appropriately.
Reference:https://experienceleague.adobe.com/en/docs/experience-manager-learn/getting-started-wknd-tutorial-de...
Thank you!

Avatar

Community Advisor

Hi,

The community's purpose is to help and guide you while you learn, rather than completing the task for you. I encourage you to read some of the resources I am attaching so you can accomplish it yourself. Before that, let me provide you with some pointers:

  1. This is a plain Java class, so there is no need for AEM knowledge. You could explore additional forums or communities outside of this one.

  2. The code in the class must be refactored before testing. The current structure of the code will make it more difficult to write any tests, so I advise you to refactor it first and make the code cleaner.

Here are some resources you can check out:

https://www.baeldung.com/junit

https://junit.org/junit5/docs/current/user-guide/ 

https://medium.com/strategio/best-practices-for-creating-java-object-classes-b4cdba3b995f

https://marcingryszko.medium.com/good-vs-bad-test-helpers-62d552004bc5

 

 

 

Hope this helps



Esteban Bustamante