When writing test classes, accessing the Standard Price Book is essential for creatingOpportunityLineItemrecords. The methodTest.getStandardPricebookId()is specifically designed to retrieve the Standard Price Book ID in a test class context. This ensures you can work with the price book without requiring@isTest(SeeAllData=true). Why not other options? B:@isTest(SeeAllData=true)is not recommended because it violates Salesforce best practices by accessing actual org data. C:@TestVisibleis used for visibility between classes but does not relate to retrieving Standard Price Book. D:Test.loadData()loads test data from static resources but is unnecessary for accessing the Standard Price Book. Salesforce Testing Framework Apex Testing Best Practices
最新のコメント (最新のコメントはトップにあります。)
generativeAI - 2025-11-22
正解は **A** です。
### 正解の解説
**A. `Test.getStandardPricebookId()` を使用して標準価格表 ID を取得します。**
最新のコメント (最新のコメントはトップにあります。)
正解は **A** です。
### 正解の解説
**A. `Test.getStandardPricebookId()` を使用して標準価格表 ID を取得します。**
Apexのテスト実行時、データは隔離(Isolation)されており、組織の本番データにはアクセスできません。しかし、**「標準価格表 (Standard Pricebook)」** は商品を追加する際などに必須となる特殊なレコードです。
これにアクセスするために、Salesforceは専用のメソッド **`Test.getStandardPricebookId()`** を提供しています。
これを使用することで、`SeeAllData=true` を使わずに、安全に標準価格表のIDを取得し、テストデータ(PricebookEntryなど)を作成することができます。
**実装例:**
```apex
@isTest
static void testTrigger() {
// 1. 標準価格表IDを取得 (これが正解のメソッド)
Id pricebookId = Test.getStandardPricebookId();
// 2. 商品を作成
Product2 prod = new Product2(Name = 'Test Product', IsActive = true);
insert prod;
// 3. 標準価格表エントリを作成 (ここには標準価格表IDが必要)
PricebookEntry pbe = new PricebookEntry(
Pricebook2Id = pricebookId,
Product2Id = prod.Id,
UnitPrice = 100,
IsActive = true
);
insert pbe;
// ...その後のテスト処理...
}
```
-----
### 不正解の解説
**B. `@isTest(SeeAllData=true)` を使用して、既存の標準価格表を削除します。**
* これは **推奨されない(不正解)** 方法です。
* 以前(かなり昔のバージョン)はこれを使うしかありませんでしたが、`Test.getStandardPricebookId()` が導入されてからは、テストの独立性を保つためにこちらを使うべきではありません。
* また、選択肢の「既存の標準価格表を**削除**します」という記述も誤りです(アクセスするためであって、削除するためではありません)。
**C. `@TestVisible` を使用して...**
* これは **不正解** です。
* `@TestVisible` は、Apexクラス内の **`private`** な変数やメソッドをテストクラスから見えるようにするためのアノテーションです。データベース上のレコード(価格表)へのアクセス権とは無関係です。
**D. `Test.loadData()` と静的リソースを使用して...**
* これは **不正解** です。
* `Test.loadData()` はカスタムデータをロードするのに...