[SalesForce] How to test partner user community

I have created a user without userrole in my testclass if I run this in my sandbox my testclass gives 100% coverage. When I try to deploy this to production it gives me 0% coverage as I figured out there is a bug in the Napili template and says user needs to have a role.

I am trying to add a role to my user and get the issue with mixed dml which I read some examples of here. I cant figure out how to use @future if the User needs a contact Id.

Test

 @isTest
private class AddContactTest{
    public static testMethod void testFunction(){                
        //Create account
        Account acc = new Account(
            name = 'TestAccount'
        );
        insert acc ;

        //Create contact for the account, which will enable partner portal for account
        contact con = new Contact(
            firstName = 'Test',
            lastname = 'TestLastname',
            accountId = acc.Id,
            email = 'test@test.com'
        );
         insert con ; 

        //Create user for the contact
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'Partner Community User' Limit 1];
        UserRole ur = [SELECT Id FROM UserRole Where name = 'Organisatie Partner Partner Gebruiker' Limit 1];
        User user1 = new User(
            username = 'test12345test@test.com',
            //contactId = con.Id,
            profileId = profile.Id,
            alias = 'test123',
            email = 'test12345@test.com',
            emailEncodingKey = 'UTF-8',
            lastName = 'Tester',
            communityNickname = 'test12345',
            timeZoneSidKey = 'America/Los_Angeles',
            localeSidKey = 'en_US',
            languageLocaleKey = 'en_US',
            UserRoleId = ur.id
        );
        insert(user1); 

        system.runAs(user1){
            Account acc1 = new Account(Name='TestAccount');
            insert acc1;
            list<Contact> listContact=new list<Contact>();
            for(Integer i=0;i<50;i++){
                Contact con1=new Contact();
                con1.LastName = i+'Contact';
                con1.AccountId = acc1.id;
                con1.email = 'email'+i+'@test.nl';
                listContact.add(con1);
            } 
            System.Test.startTest();
            Addcontact.saveContacts(listContact);
            System.AssertNotEquals(Null,[SELECT id FROM Contact]);
            System.test.stopTest();   
        }                                
    }
}

Best Answer

You should not need to specify the UserRole, but you do need to include contactId = con.Id when creating user1 so it will be properly linked to the portal contact / account. The system will automatically set UserRole as long as you set the ProfileId to a partner community profile.

Also - the owner of the account must have a role, so you'll need assign a role to your own user. See Creating a Community User via Apex from a Contact