[SalesForce] System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username

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(){
    Test.startTest();
    // 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.Category__c='Check';
        c.SubCategory__c='My Check';
        c.ContactId = con.Id;
        c.RecordTypeId = paymentRTId;    

        cases.add(c.clone(false));
        cases.add(c.clone(false));

        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 ;
    System.runAs(usr){
        cases[1].OwnerId = usr.Id;
        cases[1].RecordTypeId = legalRTId; 
        update cases;
    }

    System.assert(con != null);
    Test.stopTest();
}

Best Answer

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:

username=Math.random()+'@'+Math.random()+'.test'

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:

username=Math.random+'@'+UserInfo.getOrganizationid()+'.test'