Salesforceでテストクラス割当テストUser

2985 ワード

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='[email protected]',
 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='[email protected]',
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 }

 
中には2つの静的方法があり、1つはProfileがAdmin、指定されたPermission SetのUserを作成することであり、1つは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を作成するのに便利です