function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ms-hase-q23eems-hase-q23ee 

通常のコードから「テストコードから呼ばれている」というコンテキストの認識は可能か?

お世話になっております。
以下のようなコードがあり、引数のユーザーIDから取引先担当者->操作機械をたどってIDを返すロジックがあります。


    /**
     * ユーザーが入力したログインユーザーIDを
     * 操作機械のオブジェクトIDに変換する
     **/
    public static String getopmachineSfId(String loginUserId) {
        String opeId = '';
        try {
            User loginUser = [select contactId from User where username = :loginUserId];
            List<Contact> contacts = [select c.id, a.id from contact c, contact.account a where c.id = :loginUser.contactId];
            if (contacts.size() >0) {
                List<opmachine__c> opmachines = [select o.id from opmachine__c o, opmachine__c.Account__r a where a.id = :contacts[0].account.Id];
                if (opmachines.size() >0) {
                     opeId = opmachines[0].id ;
                }
            }
        } catch (QueryException e) {
            opeId = '';
        } catch (ListException le) {
            opeId = '';
        }
        return opeId;
    }

こちらのロジックが通常のsalesforceログイン画面や、RESTExplorerからだと間違いなくデータの取得が出来るのですが、テストコードからだと取得できない不具合が発生しています。この為、カバレッジが全く上がらず、サーバにデプロイすら出来ません。

何が起きているか、分かる方はいらっしゃいますでしょうか?テスト中のコンテキストでもUserオブジェクトに、loginUserIdが入っていることは確認できましたが、何が無くて、空文字となるのか、分かりません。

もしくは、getopmachineSfId()のロッジ側から、テストコンテキストから呼び出されたことは認識できないでしょうか?

    public static String getopmachineSfId(String loginUserId) {
        String opeId = '';
       if(呼び出しがテストコンテキストである)  { 
               return 'a1S1000000OD1pDEAT' ;
      }

原因に深入りすることは出来ないので、上記のように書きたいのですが
Best Answer chosen by ms-hase-q23ee
Taiki YoshikawaTaiki Yoshikawa
テストクラスで実行されたかの判定は『isRunningTest()』で判定可能です。
 
if (Test.isRunningTest()) {

}

こんな感じで判定できます。

Test Class
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_test.htm#apex_System_Test_isRunningTest

All Answers

Taiki YoshikawaTaiki Yoshikawa
テストクラスで実行されたかの判定は『isRunningTest()』で判定可能です。
 
if (Test.isRunningTest()) {

}

こんな感じで判定できます。

Test Class
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_test.htm#apex_System_Test_isRunningTest
This was selected as the best answer
Taiki YoshikawaTaiki Yoshikawa
テストクラス内でアクセスするデータの作成は行っているでしょうか。
テストクラス内では基本的に組織に存在するレコードにはアクセスできないので、テストクラス内でINSERTする必要があります。

また、テストクラス内で値が正しく取得できているかは、System.assertEquals()で判定可能です。