[SalesForce] Create multiple users in APEX test coverage

I have been trying to transport my change set from the developer sandbox to production and I'm getting an error when I try to do this.

The error:

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.
Another user has already selected this username.
Please select another.: [Username]"

This error only shows up went trying to upload a change set from the sandboxes to production, but not from one sandbox to another sandbox. This is misleading a bit.

The idea is to create several users to test Event with EvenRelations. All the code has being tested 100% on the sandbox. The APEX trigger, in this case, works fine and like I said it has being test with a 100% coverage result. This a small part of the code that creates the users:

`Profile p = [select id FROM Profile WHERE Name ='ProfileNmae'];

User user1 = new User();
user1.Username = 'us1@test.com';
user1.Email = 'us1@test.com';
user1.LastName = 'LastName1';
user1.FirstName = 'FirstName1';
user1.Alias ='u1';
user1.CommunityNickname ='use1';
user1.ProfileId =p.id;

user1.EmailEncodingKey='UTF-8';
user1.LanguageLocaleKey='en_US';
user1.LocaleSidKey='en_US';
user1.TimeZoneSidKey='America/Los_Angeles';
user1.Country = 'US';
user1.Title = 'Territory Manager';


insert user1;
userId.add(user1.id);


EventRelation eventRelationUser1 = new EventRelation();

eventRelationUser1.RelationId = user1.id;
eventRelationUser1.Status = 'Accepted';
eventRelationUser1.EventId = eventTestId;

insert eventRelationUser1;

system.assertEquals('Accepted', eventRelationUser1.Status);
system.assertEquals(eventRelationUser1.EventId, eventTestId);

User user2 = new User();
user2.Username = 'us2@test.com';
user2.Email = 'us2@test.com';
user2.LastName = 'LastName';
user2.FirstName = 'FirstName2';
user2.Alias ='u2';
user2.CommunityNickname ='use2';
user2.ProfileId =p.id;

user2.EmailEncodingKey='UTF-8';
user2.LanguageLocaleKey='en_US';
user2.LocaleSidKey='en_US';
user2.TimeZoneSidKey='America/Los_Angeles';
user2.Country = 'US';
user2.Title = 'Field Service Manager';

`

So this is the approach I used on the test code and it works, but that is not the case when moving the change set to production.
I have been reading and I have been trying to get a solution for this. I found out that you need to have unique users when using test codes in production, fine.
So I found this code that it will create a unique user from your code when moving test APEX codes to production:

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;
}

After trying this it looks like the first test users is not showing up as a duplicate USERNAME anymore but the second one those. Anyone knows how I can use this or any other code to make sure that the test users I have in my test code are unique, and allow me to upload the change set to production?

regards,

V

Best Answer

I have solved this error:

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.
Another user has already selected this username.
Please select another.: [Username]"

By creating this:

`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;`

And then I use this combination to obtain a unique username.

`Profile p = [select id FROM Profile WHERE Name ='Administrator'];

 User user1 = new User();
 user1.Username = uniqueName + '@test' + orgId + '.org';
 user1.Email = uniqueName + '@test' + orgId + '.org';
 user1.LastName = 'LastName1';
 user1.FirstName = 'FirstName1';
 user1.Alias = uniqueName.substring(18, 23);
 user1.CommunityNickname ='use1';
 user1.ProfileId =p.id;

 user1.EmailEncodingKey='UTF-8';
 user1.LanguageLocaleKey='en_US';
 user1.LocaleSidKey='en_US';
 user1.TimeZoneSidKey='America/Los_Angeles';
 user1.Country = 'US';
 user1.Title = 'Territory Manager';


insert user1;`

If I try to transfer my change set now I have no problems with the username. I repeat this for the second user but I created a second set of Integer radomInt and String uniqueName.

Integer randomInt2 = Integer.valueOf(math.rint(math.random()*2000000));

I notice that if I use the same randomInt for my second username the random composition of String uniqueName = orgId + dateString + randomInt; will be the same than the one for the first user and it's not unique.

But using String uniqueName2 = orgId + dateString + randomInt2; for the second user will works, creating a new username that is unique.

This is a solution. Any comments on this?

Edit 11-21-14

So far there is not problems and the code has been active for a few months. We are going to modify all test classes and add a test factory class to avoid issues like this one.

Related Topic