5
6

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.

【Salesforce初心者】トリガのテスト(Saveresult, DeleteResult)

Last updated at Posted at 2017-04-10

トリガのTestクラスを作成するためのメモです。

SalesforceのDMLで、以下の書き方があります。
Assertを入れる時の受け皿と一緒にまとめてみました。

DML Result for Assert
Insert SaveResult
Update SaveResult
Upsert UpsertResult
Delete DeleteResult
Undelete UndeleteResult
Merge MergeResult

Assertを書くときは、上記の実行結果を下記のように書けば良いかと思います:

System.assert(!result.isSuccess());

TrailheadのトリガをFireするためのテストコードが以下です(Insert, Update)。

//トリガ
trigger RestrictContactByName on Contact (before insert, before update) {
  
  //check contacts prior to insert or update for invalid data
  For (Contact c : Trigger.New) {
    if(c.LastName == 'INVALIDNAME') {  //invalidname is invalid
      c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
    }

  }
}
//RestrictContactByNameトリガのテストコード
@isTest
private class TestRestrictContactByName {

    @isTest static void TestRestrictContactByNameByInsertOneRecord(){
        //LastName = 'INVALIDNAME 'のレコードを作成し、Insertする
        Contact newCont = New Contact (FirstName = 'Jay', LastName = 'INVALIDNAME');
        //insert newCont;
        
        Test.startTest();
        Database.SaveResult result = Database.insert(newCont, false);
        Test.stopTest();
        
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
    }
    
    
    @isTest static void TestRestrictContactByNameByUpdateOneRecord(){
        //テストでのレコードをinsertし、LastNameをINVALIDNAMEにしてupdateする
        Contact oldCont = new Contact(FirstName = 'Lucy', LastName = 'Test');
        insert oldCont; 
        oldCont.LastName = 'INVALIDNAME';
        
        Test.startTest();
        Database.SaveResult result = Database.update(oldCont, false);
        Test.stopTest();

        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);

    }
}

メソッド名前が若干長いのがちょっと気になりますが、まあいいか。

5
6
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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?