function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
wt35wt35 

Error in test class: System.DmlException: DUPLICATE_USERNAME

Hi community,

 

I am getting this error while running a test class, I don't really understand why because I am not even trying to insert a user, only opportunities...

 

 

Error message:

 

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>Another user has already selected this username.<br>Please select another.: [Username] Stack Trace Class.CloseDuplicateOpportunitiesTest.test1: line 17, column 1

 

 

 

Class:

 

global class CloseDuplicateOpportunities{

   webService static String closeDuplicateOpportunities(Id contextOppId) {
       
        Opportunity contextOpp;
        List<Opportunity> relevantOpps;
        String finalMessage;
        Profile userProfile = [SELECT Name FROM Profile WHERE Id = :Userinfo.getProfileId()];


        /*********************************************************/
        /*****************AUTHORIZED USER ************************/
        /*********************************************************/
   
        try{
        contextOpp = [SELECT Id,AccountId,Owner.Name FROM Opportunity WHERE Id=:contextOppId];
        } catch(Exception e){
        System.debug('The following exception has occurred while trying to get the context opp: ' + e.getMessage());
        }
        
        
        if (   (userProfile.Name.equals('NA Telesales Rep') ||
                userProfile.Name.equals('NA Telesales Manager') ||
                userProfile.Name.equals('NA Territory Manager - Outbound')) && 
                contextOpp.Owner.Name == 'NA BS User' )
        {
            List<Opportunity> oppsToUpdate = new List<Opportunity>();
            
            oppsToUpdate.add(contextOpp);
                       
            try{
            relevantOpps = [SELECT Id,StageName,Reason_For_Closed_Lost__c FROM Opportunity WHERE 
                AccountId = :contextOpp.AccountId AND
                IsClosed = false AND
                Owner.Name like 'NA BS User' AND
                Id != :contextOpp.Id AND 
                Product_Target__c INCLUDES ('Advanced','Express Checkout Shortcut (ECS)','Pro')];
            oppsToUpdate.addAll(relevantOpps);
            } catch(Exception e){
            finalMessage = 'No relevant opportunities have been closed because either none were found or an error has happened.';
            }

            if(oppsToUpdate.size() > 0)
            {
                for (Opportunity o : oppsToUpdate)
                {
                 o.StageName = 'Closed Lost';
                 o.Reason_For_Closed_Lost__c = 'Close - TS Duplicate';
                }

                System.debug('###########oppsToUpdate '+ oppsToUpdate);
                try{
                update oppsToUpdate;
                finalMessage = relevantOpps.size() + ' similar opportunities have been closed in addition to this one';
                } catch(Exception e){
                finalMessage = 'No relevant opportunities have been closed';
                }
            }
            
        } 
           


        /*********************************************************/
        /********************NON-AUTHORIZED USER *****************/
        /*********************************************************/
        else{            
            finalMessage = 'No relevant opportunities have been closed because you do not have an authorized profile or the opportunity is not owned by NA BS User.';
        }


     return finalMessage;
    }


}

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Subramani_SFDCSubramani_SFDC

Just change ur username in test class it will solve the problem......

All Answers

hitesh90hitesh90

can you post here your test class?

because this exception is occurs because of test class code.

wt35wt35

 

Sorry I want to provide the test class in the first class...here it is:

 

@isTest
public class CloseDuplicateOpportunitiesTest {

    @isTest(SeeAllData=true) static void test1() {
    
        User oppOwner = [SELECT Id FROM User WHERE Name='NA BS User']; 
        insert oppOwner;
        Profile p = [SELECT Id FROM Profile WHERE Name='NA Telesales Rep']; 
        User u = new User(ProfileId = p.Id,Alias = 'standt', Email='standarduser@testorg.com', 
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
          LocaleSidKey='en_US', TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
        
        Account a = new Account(Name='a',BillingCountry='IE');
        insert a;
        Opportunity o1 = new Opportunity(Name='o1',CloseDate=System.Today(),AccountId=a.Id,OwnerId=oppOwner.Id,StageName='Engaged',Product_Target__c='Advanced');
        Opportunity o2 = new Opportunity(Name='o2',CloseDate=System.Today(),AccountId=a.Id,OwnerId=oppOwner.Id,StageName='Engaged',Product_Target__c='Advanced');
        insert o1;
        insert o2;
        
        System.runAs(u) {
        String finalMessage = CloseDuplicateOpportunities.closeDuplicateOpportunities(o1.Id);
        System.assertEquals(finalMessage, '1 similar opportunities have been closed in addition to this one' );
      }
        
        
    }






}

 

thanks

 

 

 

Subramani_SFDCSubramani_SFDC

Just change ur username in test class it will solve the problem......

This was selected as the best answer
wt35wt35

Yes that's what I did in the end and it worked.

Thanks