如果在测试类中seeAlldata = false,我如何创建具有系统管理员配置文件的用户

问题描述 投票:3回答:2

我想在系统管理员配置文件的测试类中创建一个User。

我遇到的问题是我有seeAllData = false,在测试类中只使用测试类中的数据。

 List<Profile> ps = [select id, name from Profile where  name = 'System Administrator'];

这可能不会返回任何值。

我们如何创建用户的任何想法

编辑

即使使用seeAllData = false,我也可以获取查询数据。那么,即使SeeAllData = false,Profile记录也是可见的?

salesforce apex-code
2个回答
6
投票

根据documentation,用户和配置文件对象被视为“用于管理组织的对象”,无论您的测试类/方法是否包含IsTest(SeeAllData=true)注释,都可以访问它们。

以这种方式可访问的其他对象包括:

  • 组织
  • 记录类型
  • ApexClass
  • ApexTrigger
  • ApexComponent
  • ApexPage

0
投票
We can use the code directly to create a role and attach it to a user with system admin profile.

@isTest static void UserCreate() { 
UserRole obj=new UserRole(Name= 'ABC'); 
insert obj; 

Profile pf= [Select Id from profile where Name='System Administrator']; 

String orgId=UserInfo.getOrganizationId(); 
String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') 

Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
String uniqueName=orgId+dateString+RandomId; 

User uu=new User(firstname = 'Alan', 
lastName = 'McCarthy', 
email = uniqueName + '@test' + orgId + '.org', 
Username = uniqueName + '@test' + orgId + '.org', 
EmailEncodingKey = 'ISO-8859-1', 
Alias = uniqueName.substring(18, 23), 
TimeZoneSidKey = 'America/Los_Angeles', 
LocaleSidKey = 'en_US', 
LanguageLocaleKey = 'en_US', 
ProfileId = pf.Id, 
UserRoleId = obj.Id); 

} 
© www.soinside.com 2019 - 2024. All rights reserved.