try catch块的测试类

时间:2014-09-18 10:32:21

标签: salesforce visualforce apex

我正在使用一个try catch block类根据permissionset given to the user捕获异常。

像这样 -

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;     
    }   
}  

我必须为此写一个test class。因此,我的方法是创建2个用户和一个权限集' xyz'在测试课上并提供' abc'对一个和xyz'的许可。到第二个。 但我无法找到一种方法来向测试类中的用户添加权限集。 任何帮助表示赞赏。

提前致谢。

1 个答案:

答案 0 :(得分:0)

试试这段代码:

public static User getUserWithSpecifiedPermSet(Set<String> permSetNames) {

    User u                      = new User();
    u.Username                  = 'test@test.com';
    u.Email                     = 'test@test.com';
    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;
}