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

时间:2023-11-10 16:42:02

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

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

TestUserHelper类如下:

 public class TestUserHelper {
public static User createUserByPermission(String permissionSetName) {
Profile pfl = [select id from profile where name='System Administrator'];//the profile which you want to assign.
//Declaring the User
User runAsUser = new User(alias = 'Admin', email='admin@testorg.com',
emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
localesidkey='en_US', profileid = pfl.Id, country='United States', CommunityNickname = 'u1',
timezonesidkey='America/Los_Angeles', username='admin@xxx_org.com' ); Insert runAsUser;
PermissionSet pSet = [SELECT ID,Label from PermissionSet WHERE Name=:permissionSetName];
PermissionSetAssignment Asign = New PermissionSetAssignment();
Asign.AssigneeId=runAsUser.ID;
Asign.PermissionSetId=pSet.ID;
Insert Asign;
Return runAsUser;
} public static User createUserByPermissionAndProfile(String permissionSetName,String profileName) {
Profile pfl = [select id from profile where name= :profileName];
//Declaring the User
User runAsUser = new User(alias = 'Admin', email='amin@testorg.com',
emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
localesidkey='en_US', profileid = pfl.Id, country='United States', CommunityNickname = 'u1',
timezonesidkey='America/Los_Angeles', username='admin@xxx_org.com' ); Insert runAsUser;
PermissionSet pSet = [SELECT ID,Label from PermissionSet WHERE Name=:permissionSetName];
PermissionSetAssignment Asign = New PermissionSetAssignment();
Asign.AssigneeId=runAsUser.ID;
Asign.PermissionSetId=pSet.ID;
Insert Asign;
Return runAsUser;
} }

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

 @isTest
private class TestUserClassUsingUserHelper { static testMethod void myUnitTest() {
User testUser = TestUserHelper.createUserByPermission('your test permisson set name');
System.RunAs(testUser) {
Test.startTest();
//TODO init data and operate like dml and assert etc
Test.stopTest();
}
}
}

总结:此篇方便以后自己写TestClass创建TestUser,有需要的可以直接用,有错误的地方欢迎指出。