5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[APEX]バッチのテストクラス作成

Last updated at Posted at 2018-02-28

Salesforceのプログラム言語であるAPEXでバッチがあるが、
バッチで即時実行のやり方がよくわからなかったので、それのメモ。
ちなみにトリガーのテストの記事はこちら

バッチの例

取引先オブジェクトの従業員数を1人加算しているだけです。

AccountBatch
public class AccountBatch implements Database.Batchable<sObject>, Database.Stateful {

    /**
     * コンストラクタ
     */
    public AccountBatch() {
    
    }

    /**
     * Start
     */
    public Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,NumberOfEmployees FROM Account';
        return Database.getQueryLocator (query);
    }
    
    /**
     * Execute
     */
    public void execute(Database.BatchableContext BC, List<Account> accountList) {

        List<Account> updAccountList = new List<Account>();
        for (Account acc : accountList) {
            acc.NumberOfEmployees  += 1;
            updAccountList.add(acc);
        }
        update updAccountList;
    }
    
    /**
     * Finish
     */
    public void finish(Database.BatchableContext BC) {
        
    }
}

テストクラスの例

バッチはTest.startTestとTest.stopTestの間に書くことでよいらしいです。

AccountBatchTest
@isTest
private class AccountBatchTest {
    
    /* 
     * 従業員数が1加算されていることをテスト
     */
    @isTest static void test_method_1() {
        
        // テストデータの作成
        List<Account> accList = Test.loadData(Account.sObjectType, 'Test_Account_Data');

        // テストの開始
        Test.startTest();
        AccountBatch batchable = new AccountBatch();
        Database.executeBatch(batchable);
        Test.stopTest();
        
        // 検証
        ist<Account> accResultList = [SELECT Id,NumberOfEmployees FROM Account];
        for (Account accNew : accResultList) {
            for (Account accOld : accList) {
                System.assertEquals(accOld.NumberOfEmployees + 1 , accNew.NumberOfEmployees);
            }
        }
    
    }
}

#参考
SFDC:Apexバッチのサンプルコード

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?