salesforce 零基础学习(五十七)Test 类中创建TestUser帮助类

我们写Test Class的时候往往都需要指定一个uesr去run test method。

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,有需要的可以直接用,有错误的地方欢迎指出。

posted @ 2016-12-21 10:11  zero.zhang  阅读(1354)  评论(0编辑  收藏  举报