1

I've been trying to make a unit test recently that requires of UserRoles with a certain PortalRole and PortalAccountId, as well as a Group related to the previous role.

I tried doing it like this:

@TestSetup
static void dataSetup() {
    Account account = TestFactory.createAccount();
    insert account;

    User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
    System.runAs(thisUser){
        UserRole role = new UserRole(Name = 'My Nice Role', PortalRole = 'Executive', PortalAccountId = account.Id);
        insert role;

        User user = TestFactory.createUser();
        user.UserRoleId = role.Id;
        insert user;

        Group grp = new Group(Type = 'RoleAndSubordinates', RelatedId = role.Id);
        insert grp;
    }
}

But the problem is the fields aren't writeable. After searching the internet for a while I found out that those fields are written by some Salesforce internal processes, but I can't seem to figure out how to achieve it. What or how do I need to insert or these records to make them have these fields?

Thanks

4
  • Normally user role is already created, Which will soql in test class and assign role id into user RoleId directly . Try doing this way.
    – NITHESH K
    Sep 18, 2017 at 12:56
  • @NITHESHK The problem is I'm working with community UserRoles which come and go. They are created for specific roles for specific accounts, but if that account is deleted, so should the roles, right? Tbh, I just started working with communities, so maybe I'm missing tons of stuff here. At the end of the day, I just want to insert an account/contact/user for a Partner Portal and get the corresponding UserRole. Maybe I don't even have to insert it. I don't really know. Sep 18, 2017 at 15:02
  • When your working with community portal. An account must related to one contact.
    – NITHESH K
    Sep 18, 2017 at 15:34
  • Create account assign account id to contact . Then access portal role through soql and assign it to user.
    – NITHESH K
    Sep 18, 2017 at 15:35

2 Answers 2

1

When a role is created in the Org, a corresponding group related to the role is automatically created. You don't have to create it again in your test class. You can just query it as below,

Group grp = [SELECT Id, Name, Type FROM Group WHERE RelatedId = :role.Id
             AND Type = 'RoleAndSubordinates' LIMIT 1];

Hope this helps you

0

I think if you create the portal user with User.PortalRole = 'Executive' it should automatically assign a UserRoleId of a matching role type, or create one on the fly.

0

You must log in to answer this question.

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