Salesforce runAsメソッドを使用するサンプル

環境
Salesforce Apex

構文
System.runAs(u){
// 処理コード
}
一般に、Apex コードはすべてシステムモードで実行され、現在のユーザーの権限やレコード
共有は考慮されません。ユーザーのレコード共有を強制実行するために、
システムメソッド runAs を使用して、コンテキストユーザーを既存のユーザーまたは
新規ユーザーに変更するテストメソッドを作成できます。runAs メソッドは、
レコード共有を適用します。
新規のコンテキストユーザーには、ユーザー権限と項目レベル権限が適用されます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// ユーザを作成する
Profile p = [Select id,name From Profile Where name = '標準ユーザ' LIMIT 1];
User user = new User(
alias = 'changfa',
username='changfa@arkgame.com.test',
email='changfa@arkgame.com',
ProfileId = p.id,
emailencodingkey='UTF-8',
lastname='changfa',
languagelocalekey='en_US',
localesidkey='en_US',
timezonesidkey='America/Los_Angeles'
);
Insert user;
Test.startTest();
// 作成したユーザで処理の実行
System.runAs(user){
// 処理コード
}
Test.stopTest();
// ユーザを作成する Profile p = [Select id,name From Profile Where name = '標準ユーザ' LIMIT 1]; User user = new User( alias = 'changfa', username='changfa@arkgame.com.test', email='changfa@arkgame.com', ProfileId = p.id, emailencodingkey='UTF-8', lastname='changfa', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles' ); Insert user; Test.startTest(); // 作成したユーザで処理の実行 System.runAs(user){ // 処理コード } Test.stopTest();
// ユーザを作成する
Profile p = [Select id,name From Profile Where name = '標準ユーザ' LIMIT 1];
 
User user = new User(
  alias = 'changfa', 
  username='changfa@arkgame.com.test',
  email='changfa@arkgame.com',
  ProfileId = p.id,
  emailencodingkey='UTF-8', 
  lastname='changfa',
  languagelocalekey='en_US', 
  localesidkey='en_US', 
  timezonesidkey='America/Los_Angeles'
);
 
Insert user;
 
Test.startTest();
 
    // 作成したユーザで処理の実行
    System.runAs(user){
        // 処理コード
    }
 
Test.stopTest();

 

IT

Posted by arkgame