Comprehensive and Detailed Explanation From Exact Extract:
By default, Apex tests run in a system context that does not respect sharing rules. However, the getAllAccounts method is defined in a with sharing class, so it does respect sharing rules. Therefore, to correctly simulate how a Standard User would see the data, the test must be run in the context of that user.
To do this, the developer should use System.runAs() to switch the test context to the Standard User, ensuring that sharing rules are enforced for the user running the test. This allows the test to correctly verify the data the user can access.
Example of Corrected Test Method:
apex
CopyEdit
@isTest
private static void getAllAccounts_StandardUser_Test() {
User standardUser = [SELECT Id FROM User WHERE Profile.Name = 'Standard User' AND UserName =
'
[email protected]' AND isActive = true LIMIT 1];
System.runAs(standardUser) {
List<Account> result = AccountsController.getAllAccounts();
System.assertEquals(20, result.size());
}
}
Reference:
Apex Testing Best Practices - Using runAs()
最新のコメント (最新のコメントはトップにあります。)
ご提示いただいたApexコード(コントローラーとテストクラス)を、セクションごとに分解して詳しく解説します。
このコードは、**「共有ルール(セキュリティ)がApexクラスとテストクラスでどのように機能するか」** を理解するための典型的な例題です。
-----
### 1\. Apex コントローラー (`AccountsController`)
このクラスは、Salesforceのデータベースからデータを取得し、Lightningコンポーネント(LWCなど)に渡す役割を持ちます。
```apex
public class with sharing AccountsController {
@AuraEnabled
public static List<Account> getAllAccounts(){ // ※本来は static が必要
return [SELECT Id, Name, Industry FROM Account];
}
}
```
*(※解説用に、メソッド呼び出し方から推測して `static` を補足しています)*
* **`with sharing`**:
* **最も重要なポイントです。**
* このキーワードがついているクラスは、**「現在実行しているユーザーの共有ルール(レコードアクセス権)」を強制的に適用**します。
* つまり、ユーザーAが実行すればAさんが見られるレコードだけ、ユーザーBならBさんが見られるレコードだけが検索結果(SOQL)に返ってきます。
* **`@AuraEnabled`**:
* このメソッドを、Lightning Web Components (LWC) や Aura コンポーネントから呼び出せるようにするためのアノテーションです。
* **`getAllAccounts()`**:
* `[SELECT ... FROM Account]` というクエリを実行し、アカウント(取引先)のリストを返します。
* `with sharing` があるため、このクエリの結果はユーザーの権限によって変化します。
-----
### 2\. Apex テストクラス (`AccountsController_Test`)
このクラスは、上記のコントローラーが正しく動くかを確認するためのテストコードです。
#### ① データ作成部分 (`@testSetup`)
テストが走る前に、テスト専用のデータ(レコード)を一時的に作成する場所です。
```apex
@testSetup
private static void makeData(){
// 1. ユーザー情報の取得
User user1 = [SELECT ... 'System Administrator' ...]; // システム管理者
User user2 = [SELECT ... 'Standard User' ...]; // 標準ユーザー
// 2. テストデータの作成 (TestUtilsは架空のヘルパークラス)
TestUtils.insertAccounts(10, u...