function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
newbiewithapexnewbiewithapex 

How do I write test class for this class?

I need to write test class for the below class. How do I do that?
public class DataUtil{

private static final String am_time = 'AM';
private static final String empty_Space = ' ';
private static final String split_Time = '\\:';
private static final string number_Twelve = '12';
    public  static Map<Id, Account> populateAccountData(Set<Id> idsSet) {    
        Map<Id,Account> accountDataMap = new Map<Id,Account>();
        Map<String, String> sObjAndAccFld = new Map<String, String>();
        Map<String, Set<Id>> sObjAndIdsMap = new Map<String, Set<Id>>();
        Map<id,Set<id>> ridAndAccIDMap = new Map<id,Set<id>>();
        Set<Id> accountIdsSet = new Set<Id>();
        
        for(Id recId: idsSet) {//Iteraing the all Related Ids
            system.debug('SSSSSSS : '+String.valueOf(recId.getSobjectType()));
            String sObjName = String.valueOf(recId.getSobjectType());
            if(sObjAndIdsMap.containsKey(sObjName)) { // checking and adding the related id to the appropriate sObject
                sObjAndIdsMap.get(sObjName).add(recId);
            }
            else {
                Set<Id> idst = new Set<Id> {recId};
                sObjAndIdsMap.put(sObjName,idst);
            }
            if(sObjName == 'Account') { //If related Id is ACCOUNT Id then add it to the accountIdsSet
                accountIdsSet.add(recId);
                Set<Id> ridSet = new Set<Id> {recId};
                ridAndAccIDMap.put(recId,ridSet);
            }
            else {//If related Id is NOT ACCOUNT Id then finding the Id related to which object 
                List<Schema.DescribeSObjectResult> describeObj = Schema.describeSObjects(new String[]{sObjName});
                Map<String, Schema.SObjectField> FsMap = describeObj[0].fields.getMap();
                for (Schema.SObjectField objField: FsMap.values()) {
                    Schema.DescribeFieldResult fieldDesc = objField.getDescribe();
                    List<Schema.sObjectType> referenceObj = fieldDesc.getReferenceTo();
                    if(!referenceObj.isEmpty()){ // determine if field is a lookup field
                        if(referenceObj[0].getDescribe() == Schema.SObjectType.Account){ // determine if field is a lookup to Account object
                            String acctFieldName = fieldDesc.getName(); // get field API name of the account lookup field
                            sObjAndAccFld.put(sObjName, acctFieldName);
                            break;
                        }              
                    }
                }
            }
        }        
        
        for(String objName : sObjAndAccFld.keySet()) {// Building Dynamic quesy and Ferching the Account Id based on the relaed object
            Set<Id> recIds = sObjAndIdsMap.get(objName);
            String fieldAPIName = sObjAndAccFld.get(objName);
            string soql = 'select id, '+fieldAPIName+' from '+objName+' where id IN: recIds';
            system.debug('QQQQQuery : '+soql);
            for(sObject sObj: database.query(soql)) {                
               //added new condition on 5/3 to check if account is null refer D 1159
              if(sObj.get(fieldAPIName) != null){
                accountIdsSet.add((id)sObj.get(fieldAPIName));// to query the account data adding the account id to accountIdsSet
                }
                if(ridAndAccIDMap.containsKey((Id)sObj.get(fieldAPIName))) {//to map related Id and account Id (One account may have multiple related Ids)
                    ridAndAccIDMap.get((Id)sObj.get(fieldAPIName)).add((Id)sObj.get('id'));
                }
                else {
                    Set<Id> ridSet = new Set<Id> {(Id)sObj.get('id')};
                    ridAndAccIDMap.put((Id)sObj.get(fieldAPIName),ridSet);
                }
            }
        }
        
        if(!accountIdsSet.isEmpty()) {
            Map<Id,Account> accountsMap = new Map<Id,Account>([select id, name, Service_Model_Indicator__c, Account_Status__c from Account where Id IN: accountIdsSet]);
            for(Id aid: ridAndAccIDMap.keySet()) { // to get account data in task or event handler based on the related Id we are adding them to map,
                for(Id rid : ridAndAccIDMap.get(aid)) {
                    accountDataMap.put(rid, accountsMap.get(aid));
                }
            }
        }
        return accountDataMap;
    }
    
     /* Method Name: FindAreaRole
      * Return Type: String
      * Parameters : String divisionNumber
      * Description: This method is used retur
      */
    public static String findArea(String divisonNumber){
        String areaRoleId = ''; 
        UserRole userRole=[Select Id,ParentRoleId,Name from UserRole where Name = : divisonNumber];
        areaRoleId = String.valueOf(userRole.ParentRoleId);
        return areaRoleId;
    }
    
    /* Method Name: getChildRoles
      * Return Type: Set<Id>
      * Parameters : String parentRoleId
      * Description: getChildRoles takes in the parentRoleId and returns set of childRoleIds. parentRoleId is not included in the set. 
    */
    public static Set<Id> getChildRoles (string  parentRoleId)
    {
        Map <String,Set<Id>> roleMap = new Map <string,Set<Id>>();
    
        // Build Map of Parent Role Id as the key with a set of it's immidiate child records as the value of the map
        for (UserRole roles  : [Select ParentRoleId, Id  From UserRole where ParentRoleId != null])
        {
            if(roleMap.containsKey(roles.ParentRoleId)  ) {
                 roleMap.get(roles.ParentRoleId).add(roles.Id);
            }
            else {
              roleMap.put(roles.ParentRoleId,  new Set<ID>{roles.Id});
            }
            //system.debug('Parent: ' + roles.ParentRoleId);
            //system.debug('Set of child: ' + roleMap.get(roles.ParentRoleId));
        }
        
        Set<Id> childRoles = getRoleSubordinateSet (roleMap,parentRoleId);
        //system.debug('Set of all childRoles: '+ childRoles);
        return childRoles;
    }
    
    /* Method Name: getRoleSubordinateSet
      * Return Type: Set<Id>
      * Parameters : Map of <ParentRoleId, Set of immidiate child records>, string of roleId
      * Description: Internal recursive method that will return a set of subordinate childRoleIds 
    */
    private static Set<Id> getRoleSubordinateSet (Map <String,Set<Id>> mapRoles, string roleId)
    {       
       Set<Id> childRoles = new Set<id>();
        
        //RK : the below line of code RoleId is added to check if the assigned to role and logged in user role division number
        childRoles.add(roleId);
       
       if(mapRoles.containsKey(roleId))
        { 
             for(Id id : mapRoles.get(roleId))
            {
                childRoles.add(id);
                //recursive call 
                childRoles.addAll(getRoleSubordinateSet(mapRoles,id));  
            }
        }
        
        return childRoles;  
    }
    
    /* Method Name: getUserRoleNames
      * Return Type: Map<Id, String>
      * Parameters : Set<Id> UserId
      * Description: getUserRoleNames takes in a set of user Ids and returns a Map with <Id:User Id, String:User Role Name>
    */
    public static Map<Id, String> getUserRoleNames(Set<Id> UserIds) {
        try{
          Map<Id, String> UserRoleNames = new Map<Id, String>();
        
          for(User usr: [SELECT UserRole.Name FROM User WHERE Id = :UserIds]){
             UserRoleNames.put(usr.id, usr.UserRole.Name);
           }
           
           return UserRoleNames;
        }
        catch(Exception e) 
        {
            return null;
        }
    }
    
    /**
     * Method Name : buildTime
     * arguments : String 
     * returnType : Datetime
     */ 
  public static Datetime buildTime(String rawTime){
        Integer hrs;
        Integer mns;
        if(rawTime.endsWith(am_time)){   
            String tme = rawTime.split(empty_Space)[0];
           
            List<String> tmestring = tme.split(split_Time);
            if(tmestring[0] == number_Twelve){
                hrs = 0;
                mns = Integer.valueOf(tmestring[1]);
            }
            else {
                hrs = Integer.valueOf(tmestring[0]);
                mns = Integer.valueOf(tmestring[1]);
            }
        }
        else {   
             String tme = rawTime.split(empty_Space)[0];
             List<String> tmestring = tme.split(split_Time);
            if(tmestring[0] == number_Twelve){
                hrs = Integer.valueOf(tmestring[0]);
                mns = Integer.valueOf(tmestring[1]);
            }
            else {                
                hrs = Integer.valueOf(tmestring[0])+12;
                mns = Integer.valueOf(tmestring[1]);
            }
        }  
        date dt = date.today();
        Datetime finalDT = Datetime.newInstance(dt.year(), dt.month(), dt.day(), hrs, mns, 0);
      //  system.debug('FFInal time'+finalDT);
        return finalDT;
    }  
    /* Method Name: getRoleSubordinateUsers
      * Return Type: Map<Id, String>
      * Parameters : Set<Id> UserId
      * Description: getUserRoleNames takes in a Role Ids and returns a set of user Ids 
    */
    public static Set<ID> getRoleSubordinateUsers(Id roleId) {

    // get all of the roles underneath the user
    Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
    
    // get all of the ids for the users in those roles
    Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where
      UserRoleId IN :allSubRoleIds]);
      
    // return the ids as a set so you can do what you want with them
    return users.keySet();

  }
	/* Method Name: getAllSubRoleIds
      * Return Type: Set<Id> currentRoleIds
      * Parameters : Set<Id> currentRoleIds
      * Description: getAllSubRoleIds takes in a set of role Ids and returns set of all Subordinate Role Ids
    	*/
  private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {

    Set<ID> currentRoleIds = new Set<ID>();

    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId
      IN :roleIds AND ParentRoleID != null])
    currentRoleIds.add(userRole.Id);

    // go fetch some more rolls!
    if(currentRoleIds.size() > 0)
      currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));

    return currentRoleIds;

  } 

}

 
Andrew GAndrew G
Hi
2 things:

1.   I would NOT be writing a test class just yet - i would be refactoring this chunk of code as you are calling a SOQL query within a FOR loop - a big No-No for hitting limits:
for(String objName : sObjAndAccFld.keySet()) {// Building Dynamic quesy and Ferching the Account Id based on the relaed object
            Set<Id> recIds = sObjAndIdsMap.get(objName);
            String fieldAPIName = sObjAndAccFld.get(objName);
            string soql = 'select id, '+fieldAPIName+' from '+objName+' where id IN: recIds';
            system.debug('QQQQQuery : '+soql);
            for(sObject sObj: database.query(soql)) {                
               //added new condition on 5/3 to check if account is null refer D 1159
              if(sObj.get(fieldAPIName) != null){
                accountIdsSet.add((id)sObj.get(fieldAPIName));// to query the account data adding the account id to accountIdsSet
                }
                if(ridAndAccIDMap.containsKey((Id)sObj.get(fieldAPIName))) {//to map related Id and account Id (One account may have multiple related Ids)
                    ridAndAccIDMap.get((Id)sObj.get(fieldAPIName)).add((Id)sObj.get('id'));
                }
                else {
                    Set<Id> ridSet = new Set<Id> {(Id)sObj.get('id')};
                    ridAndAccIDMap.put((Id)sObj.get(fieldAPIName),ridSet);
                }
            }
        }

2.  When drop a big chunk of code, help us out by removing all non-necessary code, for example, that be chunk that has been commented out.

For the basic question on how to write a test class, think of what the code is doing and mimic that with the test class.

It appears that you have a set of Ids that may or may not be Accounts.  For a test class I would create at least two records, one account and one non-account. Insert and retrieve the Ids to a Set and pass that to the method you are using.  And then test the output to see that what you expect to happens, is happening.


Good luck
Regards
Andrew



 
newbiewithapexnewbiewithapex
Thank you for replying. I will try to modify main class method first.
Raj VakatiRaj Vakati
Use this code and make on change 

Pass the your date fromate for the 

    DataUtil.buildTime(String.valueOf('PASS THE RAW DATE FORMATE'));
     

Here is the code
 
public class InsertFutureUser {
    @future
    public static void insertUser() {
        Profile objProfile = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        UserRole obj=new UserRole(Name= 'ABC'); 
        insert obj; 
        UserRole objUserRole = new UserRole(RollupDescription ='Customer Manager', Name='Test 1'); 
        objUserRole.ParentRoleId =obj.Id ;
        insert objUserRole;
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = objProfile.Id
                        ); 
        
        
        insert uu;
    }
}
 
@isTest
private class TestDataUtils{
    @isTest static void TestDeleteAccountWithOneOpportunity() {
        Test.startTest() ;
        List<Account> accts = new List<Account>();
        
        for(Integer i=0;i<10;i++) {
            Account a = new Account(Name='TestAccount' + i);
            accts.add(a);
        }
        insert accts;
        
        
        InsertFutureUser.insertUser();
        
        Account a = new Account(name='test acc',phone='9494146144');
        insert a;
        Contact con = new Contact(accountid=a.id,lastname='test con',email='lnarasimha823@gmail.com');
        insert con;
        DataUtil.populateAccountData(new Set<id>{con.Id});
        
        
        
        
        User uu =[Select Id from User limit 1];
        UserRole objUserRole =[Select Id ,Name from UserRole where ParentRoleId!=null Limit 1];
        
        Map<Id,Account> accs =new Map<Id,Account>([Select Id ,Name from Account]) ;
        DataUtil.populateAccountData(accs.keySet());
        DataUtil.findArea(objUserRole.Name) ;
        DataUtil.getRoleSubordinateUsers(objUserRole.Id);
        DataUtil.getChildRoles(objUserRole.id);
        DataUtil.getUserRoleNames(new set<Id>{uu.Id});
         DataUtil.buildTime(String.valueOf('PASS THE RAW DATE FORMATE'));
        Test.stopTest();
        
    }
    
}