How can I assign a permission set to a user in a test context?
This question is marked as unanswered, despite it was answered in the comments.
Let's revise the answer here:
PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = '<required permission set name'];
insert new PermissionSetAssignment(AssigneeId = opUser.id, PermissionSetId = ps.Id);
In addition to @patiatus answer....
Should you need to setup a custom permission without needing to care about what permission set it belongs to ....
// Given user
User userWithCustomPermission = new User (
... // setup fields for mocked User
};
System.runAs([SELECT Id FROM User WHERE Id = :UserInfo.getUserId()][0]) {
insert userWithCustomPermission;
// Given user w/permissions
PermissionSet ps = new PermissionSet(Label = 'mockPs', Name = 'mockPs');
insert ps;
// Given custom permission associated to the mocked PermissionSet
SetupEntityAccess sea = new SetupEntityAccess(
ParentId = ps.Id,
SetupEntityId = [SELECT Id FROM CustomPermission
WHERE DeveloperName = 'yourCustomPermissionApiName'][0].Id
);
insert sea;
// Given mocked Permission Set assigned to user for test
PermissionSetAssignment psa = new PermissionSetAssignment(
AssigneeId = userWithCustomPermission,
PermissionSetId = ps.Id
);
insert psa;
}
...
// When code under test invoked ...
System.runAs(userWithCustomPermission) {
new MyCode().doSomething();
}
// Then verify
... asserts