How to create an user with unique username in test class in Salesforce?

Sample Code:

  1. public static User createTestempUser(Id roleId, Id profID, String fName, String lName) {  
  2.   
  3.     String orgId = UserInfo.getOrganizationId();  
  4.     String dateString =   
  5.     String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');  
  6.     Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));  
  7.     String uniqueName = orgId + dateString + randomInt;  
  8.     User tempUser = new User(  FirstName = fName,  
  9.                             LastName = lName,  
  10.                             email = uniqueName + '@test' + orgId + '.org',  
  11.                             Username = uniqueName + '@test' + orgId + '.org',  
  12.                             EmailEncodingKey = 'ISO-8859-1',  
  13.                             Alias = uniqueName.substring(18, 23),  
  14.                             TimeZoneSidKey = 'America/Los_Angeles',  
  15.                             LocaleSidKey = 'en_US',  
  16.                             LanguageLocaleKey = 'en_US',  
  17.                             ProfileId = profId,  
  18.                             UserRoleId = roleId );  
  19.     insert tempUser;  
  20.     return tempUser;  
  21.       
  22. }  

No comments:

Post a Comment