+ Start a Discussion
sudhirn@merunetworks.comsudhirn@merunetworks.com 

Test for role USERS BY ROLE HIERARCHY

Hi, 

 I want to write a test class for below class Please suggest me how to write. 

http://blog.jeffdouglas.com/2011/02/15/find-my-salesforce-users-by-role-hierarchy/
 
public with sharing class RoleUtils {

  public static Set<ID> getRoleSubordinateUsers(Id userId) {

    // get requested user's role
    Id roleId = [select UserRoleId from User where Id = :userId].UserRoleId;
    // 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();

  }

  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;

  }

}

Thanks
Sudhir
Best Answer chosen by sudhirn@merunetworks.com
Dhanya NDhanya N
Hi Sudhir,

Please try as per the following code -
 
@isTest
private class RoleUtils_Test {
    
    @isTest static void test_RoleUtils() {
     
        UserRole objUserRole = new UserRole(RollupDescription ='Customer Manager', Name='Test 1'); 
        insert objUserRole;
        
        Profile objProfile = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        
        User objUser = new User(
          Username = getUserNamePrefix() + 'standarduser@testorg.com',
          Alias = 'standt',
          email = 'standarduser@testorg.com',
          emailencodingkey = 'UTF-8',
          LastName = 'Testing',
          LanguageLocaleKey= 'en_US',
          LocaleSidKey = 'en_US',
          ProfileId = objProfile.Id,
          TimeZoneSidKey = 'America/Los_Angeles',
          UserRoleId = objUserRole.Id
        );

        insert objUser;
        
        Test.startTest();
        RoleUtils.getRoleSubordinateUsers(objUser.Id);
        Test.stopTest();
    }
    
    public static String getUserNamePrefix(){

        return UserInfo.getOrganizationId() + System.now().millisecond();

    }   
}

Thanks,
Dhanya