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

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

Use the following method from the sample code to create an user with unique username in test class in Salesforce.

Sample Code:

public static User createTestempUser(
	Id roleId, Id profID, String fName, String lName
) {  
  
	String orgId = UserInfo.getOrganizationId();  
	String dateString =   
	String.valueof(
		Datetime.now()
	).replace(
		' ',''
	).replace(
		':',''
	).replace(
		'-',''
	);  
	Integer randomInt = Integer.valueOf(
		math.rint(
			math.random()*1000000
		)
	);  
	String uniqueName = orgId + dateString + randomInt;  
	User tempUser = new User(  
		FirstName = fName,  
		LastName = lName,  
		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 = profId,  
		UserRoleId = roleId 
	);  
	insert tempUser;  
	return tempUser;  
	  
}

Leave a Reply