连接字段的 Apex 触发器的单元测试

Unit Test for Apex Trigger that Concatenates Fields

我正在尝试为前触发器编写一个测试,该触发器从自定义对象中获取字段并将它们连接到自定义 Key__c 字段中。

触发器在沙盒中有效,现在我正在尝试将其投入生产。但是,每当我在创建购买并执行 DML 后尝试执行 System.assert/assertEquals 时,Key__c 的值总是 return 为空。我知道我可以创建一个 flow/process 来执行此操作,但我正在尝试使用代码来解决此问题以供我自己借鉴。如何在测试中正确连接字段和 return? (注释掉的断言是我到目前为止尝试过的,并且在 运行 时失败了)

trigger Composite_Key on Purchases__c (before insert, before update) {
if(Trigger.isBefore)
{
    for(Purchases__c purchase : trigger.new)
    {
        String eventName = String.isBlank(purchase.Event_name__c)?'':purchase.Event_name__c+'-';
        String section = String.isBlank(purchase.section__c)?'':purchase.section__c+'-';
        String row = String.isBlank(purchase.row__c)?'':purchase.row__c+'-';
        String seat = String.isBlank(String.valueOf(purchase.seat__c))?'':String.valueOf(purchase.seat__c)+'-';
        String numseats = String.isBlank(String.valueOf(purchase.number_of_seats__c))?'':String.valueOf(purchase.number_of_seats__c)+'-';
        String adddatetime = String.isBlank(String.valueOf(purchase.add_datetime__c))?'':String.valueOf(purchase.add_datetime__c);
        purchase.Key__c = eventName + section + row + seat + numseats + adddatetime;
    }
}

}

@isTest
public class CompositeKeyTest {
public static testMethod void testPurchase() {
    //create a purchase to fire the trigger
    Purchases__c purchase = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c=1.0,number_of_seats__c='test',add_datetime__c='test');

    Insert purchase;

    //System.assert(purchases__c.Key__c.getDescribe().getName() == 'testesttest1testtest');
    //System.assertEquals('testtesttest1.0testtest',purchase.Key__c);       
}
static testMethod void testbulkPurchase(){
    List<Purchases__c> purchaseList = new List<Purchases__c>();
    for(integer i=0 ; i < 10; i++)
    {
         Purchases__c purchaserec = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c= i+1.0 ,number_of_seats__c='test',add_datetime__c='test');
        purchaseList.add(purchaserec);
    }
    insert purchaseList;
   //System.assertEquals('testtesttest5testtest',purchaseList[4].Key__c,'Key is not Valid');
}

}

您需要在插入记录后重新查询记录才能从 triggers/database

中获取更新后的数据