Hope many of Salesforce techies came across to inserting user record in test class. The below code will help your to solve your problem on inserting user with role. I would like to suggest create a separate util class for user creation like below. You can call it where ever you need in test class.
Generally if you insert same user record details in more than one test method, then you will receive an exception as below,
Test class:
Generally if you insert same user record details in more than one test method, then you will receive an exception as below,
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>Another user has already selected this username.
To avoid such issue, randomly set the user name, email in your util method and create user like below,
To avoid such issue, randomly set the user name, email in your util method and create user like below,
Test Class Utility:
- @isTest
- public class TestUserUtil
- {
- public static User createTestUser(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 tuser = 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);
- return tuser;
- }
- }
Test class:
- @isTest
- private class TestWorkLocation
- {
- static testMethod void positiveDataInsert()
- {
- Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
- UserRole ur = new UserRole(Name = 'CEO');
- insert ur;
- User usr = TestUserUtil.createTestUser(ur.Id, pf.Id, 'Test FirstName', 'Test LastName');
- System.runAs(usr)
- {
- // Do your logic here.
- }
- }
- }