+ Start a Discussion
Abhinav MIshraAbhinav MIshra 

Create UserRole

How to Create UserRole in Test Class.
We have to create a User in the test class and have to assign UserRole to that user.
UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
User u1 = new User(FirstName = 'test',LastName='user', Alias='test', CommunityNickName='test'+generateRandomString(), Title='Inside Energy Advisor',
                          Division='Test Granite Bay', EmailEncodingKey='UTF-8',LanguageLocaleKey='en_US',LocaleSidKey='en_US',
                          TimeZoneSidKey='America/Los_Angeles', Country = 'US', ProfileId = p.Id, EmployeeNumber= '1234',  UserRoleId = portalRole.Id,isActive = true);
        
        u1.UserName = 'testUser-' + generateRandomString() + '@test.com';
        u1.Email = 'testUser-' + generateRandomString() + '@test.com';
        User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];

    System.runAs (thisUser) {

        insert u1;
    }
       
      
        User u2 = new User(FirstName = 'First', LastName='Last', Alias='test', CommunityNickName='test'+generateRandomString(), Title='Inside Energy Advisor',
                          Division='Granite Bay', EmailEncodingKey='UTF-8',LanguageLocaleKey='en_US',LocaleSidKey='en_US',
                          TimeZoneSidKey='America/Los_Angeles', Country = 'US', ProfileId = p.Id, EmployeeNumber= '12345',Supervirory_Org_ID__c = 'SUP8.12786', Job_Code__c = 926,isActive = true);
       
    	u2.UserName = 'testUser1-' + generateRandomString() + '@test.com';
        u2.Email = 'testUser1-' + generateRandomString() + '@test.com';
   		u2.ManagerId = u1.Id;
        System.runAs (thisUser) {
        insert u2;
         
        }
        User us = [SELECT id,  UserRole.Name, Manager.FirstName,Email, Manager.Id, Manager.UserRoleId,Manager.UserRole.Name from User where id = :u2.Id];

We are getting the ManagerId in the last query but unable to get the Manager.FirstName,Manager.UserRoleId and Manager.UserRole.Name .
Can we create UserRole in Test Class and assign it to the User ?
If yes then how.
Please Suggest.