Apex CreatedDate を設定する前にテストレコードを挿入するサンプル

環境
Salesfoce

構文
ApexテストメソッドTest.setCreatedDate(recordId, createdDatetime)を使用して、
テスト実行中にsObjectレコードのCreatedDateフィールドを設定することができます。

書式
setCreatedDate(recordId, createdDatetime)
テストコンテキスト sObject の CreatedDate を設定します。

@isTest(SeeAllData=true) アノテーションのあるメソッドでは setCreatedDate を使用できません。
これらのメソッドは組織内のすべてのデータにアクセスできるためです。
このメソッドは、sObject ID と Datetime 値の 2 つのパラメータを取ります。いずれも null にできません。

使用例
CreatedDate を設定する前にテストレコードを挿入します。
サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@isTest
private class SetCreatedDateTest {
static testMethod void testSetCreatedDate() {
Account a = new Account(name='myAccount');
insert a;
Test.setCreatedDate(a.Id, DateTime.newInstance(2022,11,11));
Test.startTest();
Account myAccount = [SELECT Id, Name, CreatedDate FROM Account
WHERE Name ='myAccount' limit 1];
System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2022,11,11));
Test.stopTest();
}
}
@isTest private class SetCreatedDateTest { static testMethod void testSetCreatedDate() { Account a = new Account(name='myAccount'); insert a; Test.setCreatedDate(a.Id, DateTime.newInstance(2022,11,11)); Test.startTest(); Account myAccount = [SELECT Id, Name, CreatedDate FROM Account WHERE Name ='myAccount' limit 1]; System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2022,11,11)); Test.stopTest(); } }
@isTest 
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        Test.setCreatedDate(a.Id, DateTime.newInstance(2022,11,11));
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2022,11,11));
        Test.stopTest();
    }
}

 

IT

Posted by arkgame