I have a trigger on contact insert which creates portal user for my community. I am creating a test class to cover another class where I am using the user and its contact. To cover the test class I needed to create a contact and user. I have created a contact and tried to query user for the contact I got no row for assignment to list. I have also tried to create a user for the contact it worked in sandbox but when tried to deployed it has given me error for Portal User already exist Does anyone have idea how to resolve this.

Contact ct = new Contact();
        ct.FirstName = 'Test';
        ct.LastName= 'Test';
        ct.Email='[email protected]';
        insert ct;

        Profile p1 = [SELECT Id FROM Profile WHERE Name='Community User (Volume)']; 
        //here I have tried using query 
        // User user01 = [select id from user where contactId =: ct.id]; 
        // system.debug(user01);
        User user01 = new User(
                alias ='test',
                email = '[email protected]',     
                emailencodingkey = 'UTF-8', 
                firstname = 'firstName', 
                lastname = 'lastname', 
                languagelocalekey = 'en_US', 
                localesidkey = 'en_GB', 
                contactId = ct.Id,
                timezonesidkey = 'Europe/London', 
                username = '[email protected]',
                ProfileId = p1.id,
                IsActive = true);

    //code here
  • can you check if similar user name already exists in your organization which might be causing the issue.
    – sunny
    Apr 21, 2017 at 18:37

2 Answers 2


Can you check if similar user name already exists in your organization which might be causing the issue. Since it is not possible to have any two user name similar all over salesforce. Even internal user and portal user can not have similar user name.

  • No there is no user similar to this user name. Apr 24, 2017 at 5:36
  • @LavikaVaishnav It should be unique across all the organisations. Try appending some word after gmail.com in your user name
    – sunny
    Apr 24, 2017 at 5:38
  • 1
    Resolved it by querying user which created with contact. I was forgetting recordId for contact. Apr 25, 2017 at 11:15

User name is unique across all orgs. Random usernames that has test domains and 12345 numerics might be an issue sometimes. I faced the similar issue in the past. Its better to build emails and usernames in such a way that they are unique and chance of possible duplication is low. I prefer appending with company name as domain or adding system.now() or current time at the end. If its a user name, you can add sandbox name as well.

Instead of [email protected], try something like

u.Username = testuser@mycompnay+string.valueof(system.now());

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .