To fix “portal account owner must have a role” Error in Salesforce Community Unit Test

In Salesforce, if you’re trying to run Unit Test with a Non-Role user, which includes part of creating Portal / Community User test data, the following error will be occured, that is because the portal account’s owner does not have a role to be assigned.

System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, portal account owner must have a role

Here is the sample code that can explain this case.

Solution

The fix this kind of error, you can assign a role in User edit page,
User Edit  xgeek   Salesforce   Developer Edition Or run as a user who has a UserRole in test code, as the below code.



Enjoy it!