I have a class that creates a user from a contact record, so I uses the Salesforce knowledge article to make sure the email address of the test contact is unique, so it can generate a unique username, but I'm still getting the duplicate username error.

What could be causing this?

Here is my test class:

public with sharing class CreateCommunityUser_Test {
public static void testUserCreation(){
    ID StandardAccountRecordID = [SELECT ID FROM RecordType WHERE SobjectType = 'Account' AND Name = 'Standard Account' LIMIT 1].Id;

    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;

    List<Account> accountsToInsert = new List<Account>();
    Account testAccount = new Account(
        recordTypeId = StandardAccountRecordID
    testAccount = (Account)TestFactory.createSObject(testAccount);
    insert accountsToInsert;

    Contact c = new Contact(
        FirstName = 'User',
        LastName = 'Test',
        AccountId = testAccount.Id,
        TDW_Access_Type__c = 'Product',
        Email = uniqueName + '@test' + orgId + '.org'

    insert c;
    List<Id> contacts = new List<Id>();

    // Set mock callout class 
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    // Call method to test.
    // This causes a fake response to be sent
    // from the class that implements HttpCalloutMock. 

Here's the class:

public without sharing class CreateCommunityUser {
@InvocableMethod(label='Create Community User' description='Creates TDW Access Community User' category='Contact')
public static void createExternalUser(List<Id> contactIds){
    Id contactId = contactIds[0];
    Id userProfileId = [SELECT Id FROM Profile WHERE Name = 'TDW Access User' LIMIT 1].Id;
    Contact userContact = [SELECT Email,FirstName,LastName, TDW_Access_Type__c,AccountId  FROM Contact WHERE Id = :contactId LIMIT 1];
    User u = new User();
    u.Username = userContact.Email;
    u.Email = userContact.Email;
    u.FirstName = userContact.FirstName;
    u.LastName = userContact.LastName;
    u.Community_Experience__c = userContact.TDW_Access_Type__c;
    u.UserPreferencesHideS1BrowserUI = true;
    u.ProfileId = userProfileId;
    u.ContactId = userContact.Id;
    u.UserPreferencesHideSfxWelcomeMat = true;
    u.LocaleSidKey = 'en_US';
    u.LanguageLocaleKey = 'en_US';
    u.UserPermissionsSFContentUser = true;
    u.Alias = userContact.FirstName.left(4) + '.' + userContact.LastName.left(3);
    u.TimeZoneSidKey = 'America/Chicago';
    u.EmailEncodingKey = 'ISO-8859-1';

    // generating unique value for community nickname. 
    String nickname = ((userContact.FirstName != null && userContact.FirstName.length() > 0) ? userContact.FirstName.substring(0,1) : '' ) + userContact.LastName.substring(0,1);
            nickname += String.valueOf(Crypto.getRandomInteger()).substring(1,7);
    u.CommunityNickname = nickname;

    System.debug('Creating user');

    insert u;

    System.debug('New user created with Id: ' + u.Id);


  • Check this ,if it clarifies most of it? May 6, 2021 at 7:57
  • 2
    Yes, I've seen that issue, which is why I built the unique name string as recommended by the Salesforce Knowledge article. So it should be a unique user name across all environments in Salesforce... May 6, 2021 at 13:49

1 Answer 1


The issue was that the CreateCommunityUser class was being invoked by a flow when the new contact was created, and then invoked again when I called CreateCommunityUser.createExternalUser(contacts);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.