There is a class in which i am using a try catch block
which catch exception based on permissionset given to the user
.
Something like this -
public pageReference backtomainpage(){
try{
PermissionSet PS=[Select p.Name, p.Id From PermissionSet p where p.Name='abc' limit 1];
PermissionSetAssignment PSA=[Select PermissionSetId, Id, AssigneeId From PermissionSetAssignment where PermissionSetId=:PS.Id and AssigneeId=:UserInfo.getUserId()];
pageReference pg = new pageReference('/apex/page1'+currentOpp.id);
pg.setRedirect(true);
return pg;
}
catch(Exception e){
pageReference pg = new pageReference('/apex/page2+currentOpp.id);
pg.setRedirect(true);
return pg;
}
}
I have to write a test class
for this. So for this , my approach is to create 2 users and a permission set 'xyz' in test class and provide 'abc' permissionset to one and 'xyz' to 2nd one.
But I am not able to find a way to add permissionset to a user in test class.
Any help is appreciated.
Thanks in advance.
Try this code:
public static User getUserWithSpecifiedPermSet(Set<String> permSetNames) {
User u = new User();
u.Username = '[email protected]';
u.Email = '[email protected]';
u.Lastname = 'user';
u.Firstname = 'test';
u.Alias = 'test';
u.ProfileId = [SELECT Id FROM Profile WHERE Name = 'profile name'].Id;
u.TimeZoneSidKey = 'GMT';
u.LocaleSidKey = 'en_US';
u.EmailEncodingKey = 'ISO-8859-1';
u.LanguageLocaleKey = 'en_US';
u.UserPermissionsMobileUser = false;
insert u;
List<PermissionSetAssignment> psas = new List<PermissionSetAssignment>();
for (PermissionSet ps : [SELECT Id FROM PermissionSet WHERE Name = :permSetNames]) {
psas.add(new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id));
}
insert psas;
return u;
}