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
Salesforce BlitzSalesforce Blitz 

Create Test class for creating users with roles

HI guys,

I have a class which fetches all users below a particular role in a role hierarchy and sends mail to those whio have not edited in last 1 week.

I need to write a test class to it.

I need to Create few users.In which one should be Teal head of set of users.

How do i need to create  roles in role hierarchy and
how to create  multiple users in test class with Roles

Kindly reply asap. urgnt Req

Thanka s lot in adv,
Laxman jagz
Alexander TsitsuraAlexander Tsitsura
Hi Laxman ,

For create role use code below
UserRole r = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role');
insert r;
For create user
User u = new User(
     ProfileId = [SELECT Id FROM Profile WHERE Name = 'YOUR PROFILE'].Id,
     LastName = 'last',
     Email = 'puser000@amamama.com',
     Username = 'puser000@amamama.com' + System.currentTimeMillis(),
     CompanyName = 'TEST',
     Title = 'title',
     Alias = 'alias',
     TimeZoneSidKey = 'America/Los_Angeles',
     EmailEncodingKey = 'UTF-8',
     LanguageLocaleKey = 'en_US',
     LocaleSidKey = 'en_US',
     UserRoleId = r.Id
);

For create many users you need add all to list and then insert all in one transaction for avoid dml limit.

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Thanks,
Alex
Arunkumar RArunkumar R
Hi Laxman,

Please have a look on the similar post,

https://developer.salesforce.com/forums/ForumsMain?id=906F0000000BYaZIAW
Yachana YachanaYachana Yachana
Hi Laxman

You can also try this code:-

@isTest static void UserCreate() { 
UserRole obj=new UserRole(Name= 'ABC'); 
insert obj; 

Profile pf= [Select Id from profile where Name='System Administrator']; 

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 = pf.Id, 
UserRoleId = obj.Id); 



As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.
Raj VakatiRaj Vakati
@isTest
private class AssignedAdvisorControllerTest{
    @testSetup
    static void setupTestData(){
        
        Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        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 = pf.Id
                        ); 
        
        
        insert uu;
        Account account_Obj = new Account(Name = 'Test User', Assigned_Adviser__c = uu.id);
        Insert account_Obj; 
        
    }
    static testMethod void test_getAssignedAdvisor(){
        System.Test.startTest();
        Account  account_Obj  =  [SELECT Id,Name,Assigned_Adviser__c from Account Limit 1];
        //ystem.assertEquals(true,account_Obj.size()>0);
        AssignedAdvisorController obj01 = new AssignedAdvisorController();
        AssignedAdvisorController.getAssignedAdvisor(account_Obj.Id);
        System.test.stopTest();
    }
    static testMethod void test_getAdvisorPhone(){
        System.test.startTest();
        Account  account_Obj  =  [SELECT Id,Name,Assigned_Adviser__c from Account Limit 1];
        // System.assertEquals(true,account_Obj.size()>0);
        AssignedAdvisorController obj01 = new AssignedAdvisorController();
        AssignedAdvisorController.getAdvisorPhone(account_Obj.Id);
        System.test.stopTest();
    }
}

 
Pramod DhokanePramod Dhokane
Your first method setupTestData() did not worked, Exception --> System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: UserRole: []