Memos About Salesforce

Salesforceにハマってたこと!

Salesforce SFDC DML 例外テスト カバ率 アップ方法 apex test class テストクラス

こんにちは、管理人の@Salesforce.Zです。

バッチやクラスなどを開発する際に、try catch ブロックを使うのが普通なことに対して、

テストクラスを書く時に、クラスのカバ率を上げたい場合に、どうコーディングするかについて

僕のやり方を共有します。ご参考になれば幸いです。 ※あくまでも僕の場合

読んだら得ること

★ クラスのカバ率を上げるためtry catchブロックの通る方法

目次

例外ブロックのテスト

try catchブロックは、いろいろキャッチできるが、今回、DMLの例外だけを例にする ほかは流用で、良いと考える

DMLの例外テスト

アルゴリズムは下記になる

1.本体のクラスに例外を発生させるコードを記載する

2.例外発生コードに条件を付ける(テストクラス実行時のみ通る、かつ、特定変数がtrueの場合)

サンプルクラス

/*******************************************************************************
*このクラスはテストクラスがテストしたいクラス
******************************************************************************/
public with sharing RealClass {
    @testVisible
    private static Boolean isDMLExceptionTest;

    // constractor
    public RealClass () {

    }

    // your logic method
    public void doSth (){
        try {
            // your logic

            // for coverage logic
            if (Test.isRunningTest() && isDMLExceptionTest != null && isDMLExceptionTest){
                // このまま、新規取引先を作成すると、取引先名がないため、insert エラーになる
                insert account();
            }
        } catch (DmlException de) {
            // error handling logic
        }
    }
}

サンプルテストクラス

/*******************************************************************************
*このクラスはテストクラスがテストしたいクラス
******************************************************************************/
@isTest
private class DailyUpdateRelatedEventSPBatchTest {
    // 実行ユーザ この外部クラスは略
    private static User adminUser = YourDataUtil.executeAdminUser();

    @isTest
    private static testMethod void BatchNormalTest(){
        // test prepare block
        System.debug('■■■テスト準備■■■');
        RealClass.isDMLExceptionTest = false;//DML エラーさせない、通常テストを行う

        System.debug('■■■テスト開始■■■');
        Test.startTest();
            // write you want to test code
        Test.stopTest();

        System.debug('■■■結果検証■■■');
        // write you want to verify code
    }

    @isTest
    private static testMethod void BatchAbnormalTest(){
        // test prepare block
        System.debug('■■■テスト準備■■■');
        RealClass.isDMLExceptionTest = true;//DML エラーさせる catchブロックを通る

        System.debug('■■■テスト開始■■■');
        Test.startTest();
            // write you want to test code
        Test.stopTest();

        System.debug('■■■結果検証■■■');
        // write you want to verify code
    }

}

終わりに

Test クラス