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,有需要的可以直接用,有错误的地方欢迎指出。
作者:zero
博客地址:http://www.cnblogs.com/zero-zyq/
本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接
如果文章的内容对你有帮助,欢迎点赞~
为方便手机端查看博客,现正在将博客迁移至微信公众号:Salesforce零基础学习,欢迎各位关注。