[SalesForce] Create a Customer Community User in Test to Login Connected Application

Please help out in any way possible with the below challenge;

We have an application connected to salesforce which is logged in by our customers(accounts) through community users which are created for their accounts.

These community users are created through the class: "site.createExternalUser(user, accountId, password)" when the customer registers himself on the application from the app interface.

However, now we are trying to create some test customer community users to test a few things. I tried using site.createExternalUser but it did not work.
If someone can help me with this, let me know.

OR

Secondly, I am trying to directly create the customer community users through an apex class and the user is created but I do not know how to setup the "PASSWORD" for these users using the code. I mean when I try to login my app, what would be the password to login?
My code to create a new contact+user & then assign them to an account is below and the contact+user are created successfully but I am unable to login the app (most probably because I do not have a password)

public class createUsersv4 {


    public user createPartnerUser(){  

        Account a = [select name from Account where Id='0010Q00000DO8b7QAD'];
       // system.debug('Account = ' + a.Name);

        Contact c = New Contact(LastName = 'Test', AccountID = a.id);
        insert c;
       // system.debug('Contact = ' + c.Id);

        Profile p = [SELECT Id FROM Profile WHERE Name = 'Customer Community user' LIMIT 1];

        user u = New User(
            UserName = 'test_' + math.random() + '@test.com',
            FirstName = 'Test-First',
            LastName = 'Test-Last',
            Alias = 'test',
            email = 'test' + math.random() + '@test.com',
            CommunityNickName = string.valueOf(math.random()).substring(0,6),
            ProfileID = p.id,
            TimeZoneSidKey = 'America/New_York', 
            LocaleSidKey = 'en_US', 
            EmailEncodingKey = 'UTF-8', 
            LanguageLocaleKey = 'en_US',
            ContactID = c.Id

            );

        system.debug('User = ' + u.Id);

        insert u;

        return u;


    }

}

Best Answer

If you are just hard coding the user's password for testing ONLY you could, after the user is inserted add another line as below:

insert u;
System.setPassword(u.Id, 'yourpasswordhere');
return u;
Related Topic