Skip to main content
3 月 5 日~ 6 日にサンフランシスコで開催される TDX (Salesforce+ でも配信) で「Developer Conference for the AI Agent Era (AI エージェント時代に向けた開発者向けカンファレンス)」にぜひご参加ください。お申し込みはこちら

変更イベントトリガーのテスト

学習の目的

この単元を完了すると、次のことができるようになります。

  • Apex 変更イベントトリガーの Apex テストクラスを記述する。
  • テストを実行し、Apex 変更イベントトリガーのテストカバー率を提示する。
メモ

メモ

日本語で受講されている方へ
Challenge は日本語の Trailhead Playground で開始し、かっこ内の翻訳を参照しながら進めていってください。Challenge での評価は英語データを対象に行われるため、英語の値のみをコピーして貼り付けるようにしてください。日本語の組織で Challenge が不合格だった場合は、(1) この手順に従って [Locale (地域)] を [United States (米国)] に切り替え、(2) [Language (言語)] を [English (英語)] に切り替えてから、(3) [Check Challenge (Challenge を確認)] ボタンをクリックしてみることをお勧めします。

翻訳版 Trailhead を活用する方法の詳細は、自分の言語の Trailhead バッジを参照してください。

変更イベントトリガーのテスト

変更イベントトリガーの記述方法を学んだところで、そのトリガーのテストを記述してみましょう。トリガーをテストすることは推奨されるだけでなく、プラットフォームによって適用されます。Apex トリガーをパッケージ化または本番環境にリリースする前に、Apex テストを実施し、十分なコードカバー率を達成する必要があります。 

Apex トリガーのテストカバー率を提示するには、1 つ以上のテストメソッドを含む Apex テストクラスを記述します。変更イベントトリガーのテストメソッドは次のような構造になります。

@isTest static void testChangeEventTrigger() {
    // Enable all Change Data Capture entities for notifications.
    Test.enableChangeDataCapture();
    // Insert one or more test records
    // ...
    // Deliver test change events
    Test.getEventBus().deliver();
    // Verify the change event trigger’s execution
    // ...
}

テストメソッドに含める 1 つ目のステートメントは次のとおりです。

Test.enableChangeDataCapture();

このステートメントによって、変更データキャプチャのすべてのエンティティが有効になり、テストメソッドの Salesforce レコードの変更によって変更イベントトリガーが起動することを確認できます。このメソッドは、すべてのエンティティをテストの目的のみで有効にするもので、組織の変更データキャプチャエンティティの選択には影響ありません。

変更データキャプチャを有効にしたら、何らかの DML 操作を実行して、Test.getEventBus().deliver() メソッドをコールします。このメソッドは、テストイベントバスから対応する変更イベントトリガーにイベントメッセージを配信して、トリガーを起動させます。

Test.getEventBus().deliver();

テスト変更イベントメッセージは、Salesforce イベントバスとは分離したテストイベントバスに公開されます。これらのメッセージは Salesforce に保持されず、テストクラス外のイベントチャネルにも配信されません。再実行 ID などのテスト変更イベントメッセージのプロパティは、テストのコンテキストでリセットされ、テストイベントメッセージの値のみが反映されます。

トリガーのテストの作成と実行

ではここで、TestEmployeeChangeTrigger というテストクラスを実際に作成してみましょう。クラスのテストメソッドは、Employee (従業員) テストレコードを作成して、そのレコードを更新します。これらの操作ごとに、Employee (従業員) 変更イベントのトリガーが起動します。このテストでは、トリガーが作成した ToDo を照会して ToDo 数を検証する方法でトリガーの実行を確認します。

テストクラスを開発者コンソールで実行すると、[Logs (ログ)] タブにデバッグログが表示されます。Apex テストの場合は、自動プロセスエンティティの [設定] でデバッグログを設定する必要がありません。

テストクラスを作成する手順は、次のとおりです。

  1. 開発者コンソールで、[File (ファイル)] | [New (新規)] | [Apex Class (Apex クラス)] を選択します。
  2. [Name (名前)] 項目に、TestEmployeeChangeTrigger というトリガーの名前を入力します。
  3. デフォルトのコンテンツを次のコードに置き換えます。
@isTest
public class TestEmployeeChangeTrigger {
    @isTest static void testCreateAndUpdateEmployee() {
        // Enable all Change Data Capture entities for notifications.
        Test.enableChangeDataCapture();
        // Insert an Employee test record
        insert new Employee__c(Name='e-101',
            First_Name__c='Astro',
            Last_Name__c='Test',
            Tenure__c=1);
        // Call deliver to fire the trigger and deliver the test change event.
        Test.getEventBus().deliver();
        // VERIFICATIONS
        // Check that the change event trigger created a task.
        Task[] taskList = [SELECT Id,Subject FROM Task];
        System.assertEquals(1, taskList.size(),
            'The change event trigger did not create the expected task.');
        // Update employee record
        Employee__c[] empRecords = [SELECT Id,OwnerId,First_Name__c,Tenure__c FROM Employee__c];
        // There is only one test record, so get the first one
        Employee__c emp = empRecords[0];
        // Debug
        System.debug('Retrieved employee record: ' + emp);
        // Update one field and empty another
        emp.First_Name__c = 'Codey';
        emp.Tenure__c = null;
        update emp;
        // Call deliver to fire the trigger for the update operation.
        Test.getEventBus().deliver();
        // VERIFICATIONS
       // Check that the change event trigger created a task.
       // We should have two tasks now, including one from the first trigger invocation.
      Task[] taskList2 = [SELECT Id,Subject FROM Task];
      System.assertEquals(2, taskList2.size(),
          'The change event trigger did not create the expected task.');
    }
}
  1. テストクラスウィンドウで、[Run Test (テストの実行)] をクリックします。テストが終了すると、[Tests (テスト)] タブにテストの実行状況が表示されます。
  2. [Tests (テスト)] タブをクリックして、[Overall Code Coverage (全体のコードカバー率)] ペインを展開します。EmployeeChangeTrigger のコードカバー率は 100% で、これがこのテストの実行結果です。

変更イベントトリガーを記述してテストクラスを指定できたため、本番環境にリリースできます。

リソース

ハンズオン Challenge

+500 ポイント

準備を始めましょう

この 単元 は各自のハンズオン組織で実行します。[起動] をクリックして開始するか、組織の名前をクリックして別の組織を選びます。

あなたの Challenge

Write a Test Class
Create a test method to provide test coverage for the OpportunityChangeTrigger that you created in the previous unit’s challenge.

Prework: Pass the previous unit’s challenge to create the trigger.
  • Create an Apex test class for your trigger modeled after the example TestEmployeeChangeTrigger code:
    • Class Name: TestOpportunityChangeTrigger
    • Method Name: testCreateAndUpdateOpportunity
  • Copy the body of the test method from the TestEmployeeChangeTrigger example class. You will modify it next.
  • In the test method, keep the first statement: Test.enableChangeDataCapture();
  • Create an opportunity:
    • Name: Sell 100 Widgets
    • StageName: Prospecting
    • CloseDate: Date.today().addMonths(3)
  • Call Test.getEventBus().deliver(); to fire the trigger.
  • Delete the verification section because you don't need to verify the trigger execution yet. You will do so later.
  • Modify the SOQL query to retrieve the StageName field from Opportunity.
    • Opportunity[] oppRecords = [SELECT Id,StageName FROM Opportunity];
    • Opportunity opp = oppRecords[0];
  • Update the stage name to Closed Won.
    • opp.StageName = 'Closed Won';
    • update opp;
  • Call Test.getEventBus().deliver(); to fire the trigger.
  • Query Task records using a SOQL query and verify that one task is returned.
    • Task[] taskList = [SELECT Id,Subject FROM Task];
    • System.assertEquals(1, taskList.size(), 'The change event trigger did not create the expected task.');
  • Run the test class and ensure that it passes and provides 100% coverage for the trigger.
Salesforce ヘルプで Trailhead のフィードバックを共有してください。

Trailhead についての感想をお聞かせください。[Salesforce ヘルプ] サイトから新しいフィードバックフォームにいつでもアクセスできるようになりました。

詳細はこちら フィードバックの共有に進む