Not sure why I am getting the below errro

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.
The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). : [Username]

Here is Test class which is developing.

private static Id RTId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Payment').getRecordTypeId(); 
private static Id paymentRTId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Auth Payment').getRecordTypeId();

static testMethod void testSharingReplication(){
    // Create Contact
    Contact con = new contact(LastName='Raj', FirstName='Kumar');
    insert con;

    // Create Standard User
    Profile standardProfile = [SELECT Id FROM Profile WHERE Name='Standard User']; 
    User standardUser = new User(Alias = 'standt', Email='standarduser@testorg.com', 
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = standardProfile.Id, 
        TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');

    Case c = new Case();
    List<Case> cases = new List<Case>();
    System.runAs(standardUser) {
        // Create Case
        c.SubCategory__c='My Check';
        c.ContactId = con.Id;
        c.RecordTypeId = paymentRTId;    


        cases[0].OwnerId = standardUser.Id;
        update cases;

    // Create System Admin
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    User usr = new User(Alias = 'admin', Email='adminuser@testorg.com', 
                        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                        LocaleSidKey='en_US', ProfileId = p.Id, 
                        TimeZoneSidKey='America/Los_Angeles', UserName='adminuser@testorg.com');
    insert usr ;
        cases[1].OwnerId = usr.Id;
        cases[1].RecordTypeId = legalRTId; 
        update cases;

    System.assert(con != null);

The user 'standarduser@testorg.com' already exists somewhere, so you can't use that name. Typically, I recommend using a random number generator to choose a unique value, such as:


This basically guarantees that you won't conflict with existing users.

An alternative would be to use something like your org ID in the username:

  • last one is more favourable Jan 19 '18 at 6:07
  • username=Math.random()+'@'+UserInfo.getOrganizationid()+'.test' - Should be like this thanks
    – Kanika
    Jan 19 '18 at 8:53

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.