[SalesForce] How to Create Person Account Portal User in Test class

How to i Create Person Account Portal User in Test class. I am using Site.createPersonAccountPortalUser(u, ownerId, password); to create User.

Best Answer

You have to first create the Person Account (as a User with assigned Role) and then use the generated PersonContactId field on Person Account for User.ContactId ... something like this:

    UserRole r = new UserRole(name = 'TEST ROLE');
    Database.insert(r);

    User userWithRole = new User(alias = 'hasrole', email='userwithrole@roletest.com', userroleid = r.id,
                                 emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
                                 localesidkey='en_US', profileid = UserInfo.getProfileId(), 
                                 timezonesidkey='America/Los_Angeles', username='userwithrole@testorg.com');
    Account a;
    System.runAs(userWithRole){
        String recordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
        a = new Account(RecordTypeId = recordTypeId, FirstName = 'TestPersonAccountFirst', LastName = 'TestPersonAccountLast', PersonEmail = 'test@user.com');
        insert a;
    }
    Account acc = [Select PersonContactId From Account Where Id = :a.Id];
    Profile p = [SELECT Id FROM Profile WHERE Name = :COMMUNITY_PROFILE LIMIT 1];
    User u = new User(
        FirstName = 'TestFirstName',
        LastName = 'TestLastName',
        Email = 'test@user.com',
        Username = 'test@user.com',
        Alias = 'TestPA', 
        TimeZoneSidKey = 'GMT', 
        LocaleSidKey = 'en_US', 
        EmailEncodingKey = 'UTF-8', 
        ProfileId = p.Id, 
        LanguageLocaleKey = 'en_US',
        ContactId = acc.PersonContactId);
    insert u;
Related Topic