Salesforce中测试类分配测试User

TestUserHelper类如下:

 

 1 public class TestUserHelper {
 2     public static User createUserByPermission(String permissionSetName) {
 3         Profile pfl = [select id from profile where name='System Administrator'];//the profile which you want to assign.
 4         //Declaring the User
 5         User runAsUser = new User(alias = 'Admin', email='admin@testorg.com',
 6                                   emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
 7                                   localesidkey='en_US', profileid = pfl.Id,  country='United States', CommunityNickname = 'u1',
 8                                   timezonesidkey='America/Los_Angeles', username='admin@xxx_org.com' );
 9         
10         Insert runAsUser;     
11         PermissionSet pSet = [SELECT ID,Label from PermissionSet WHERE Name=:permissionSetName];
12         PermissionSetAssignment Asign = New PermissionSetAssignment();
13         Asign.AssigneeId=runAsUser.ID;
14         Asign.PermissionSetId=pSet.ID;
15         Insert Asign;      
16         Return runAsUser; 
17     }
18     
19     public static User createUserByPermissionAndProfile(String permissionSetName,String profileName) {
20         Profile pfl = [select id from profile where name= :profileName];
21         //Declaring the User
22         User runAsUser = new User(alias = 'Admin', email='amin@testorg.com',
23                                   emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
24                                   localesidkey='en_US', profileid = pfl.Id,  country='United States', CommunityNickname = 'u1',
25                                   timezonesidkey='America/Los_Angeles', username='admin@xxx_org.com' );
26         
27         Insert runAsUser; 
 //        权限的设置 
28         PermissionSet pSet = [SELECT ID,Label from PermissionSet WHERE Name=:permissionSetName];
29         PermissionSetAssignment Asign = New PermissionSetAssignment();
30         Asign.AssigneeId=runAsUser.ID;
31         Asign.PermissionSetId=pSet.ID;
32         Insert Asign;      
33         Return runAsUser; 
34     }
35     
36 }

 

里面有两个静态方法,一个是创建一个Profile为Admin,指定的Permission Set的User,一个是指定Profile,指定Permission Set的User。相关Test Class引用:

 

 1 @isTest
 2 private class TestUserClassUsingUserHelper {
 3 
 4     static testMethod void myUnitTest() {
 5         User testUser = TestUserHelper.createUserByPermission('your test permisson set name');
 6         System.RunAs(testUser) {//以这个测试身份去运行  
 7             Test.startTest();
 8             //TODO init data and operate like dml and assert etc
 9             Test.stopTest();
10         }
11     }
12 }

 

总结:此篇方便以后自己写TestClass创建TestUser

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值