1

我已经为 Saleforce 触发器编写了一个测试。Account_Status_Change_Date__c每当“Account_Status__c”更改时,触发器会将值更改为当前日期。

我已经通过 Web GUI 实际更改了帐户状态的值,并且帐户状态更改日期确实设置为当前日期。但是,我的测试代码似乎没有触发这个触发器。我想知道人们是否知道这样做的任何原因。

我的代码如下:

@isTest
public class testTgrCreditChangedStatus {

    public static testMethod void testAccountStatusChangeDateChanged() {

        // Create an original date
        Date previousDate = Date.newinstance(1960, 2, 17);

        //Create an Account
        Account acc = new Account(name='Test Account 1');
        acc.AccountNumber = '123';
        acc.Customer_URN_Number__c = '123';
        acc.Account_Status_Change_Date__c = previousDate;
        acc.Account_Status__c = 'Good';
        insert acc;

        // Update the Credit Status to a 'Bad Credit' value e.g. Legal
        acc.Account_Status__c = 'Overdue';
        update acc;

        // The trigger should have updated the change date to the current date
        System.assertEquals(Date.today(), acc.Account_Status_Change_Date__c);
    }
}

trigger tgrCreditStatusChanged on Account (before update) {

    for(Account acc : trigger.new) {
        String currentStatus = acc.Account_Status__c;
        String oldStatus = Trigger.oldMap.get(acc.id).Account_Status__c;

        // If the Account Status has changed...
       if(currentStatus != oldStatus) {
            acc.Account_Status_Change_Date__c = Date.today();
        }
    }
}
4

1 回答 1

3

您不需要触发器来执行此操作。可以通过 Account 上的简单工作流规则来完成。但是,您的测试代码的问题是您需要在更新后查询帐户以获取帐户字段中的更新值。

public static testMethod void testAccountStatusChangeDateChanged() {

    ...
    insert acc;

    Test.StartTest();
    // Update the Credit Status to a 'Bad Credit' value e.g. Legal
    acc.Account_Status__c = 'Overdue';
    update acc;
    Test.StopTest();

    acc = [select Account_status_change_date__c from account where id = :acc.id];
    // The trigger should have updated the change date to the current date
    System.assertEquals(Date.today(), acc.Account_Status_Change_Date__c);
}
于 2012-07-26T16:05:36.837 回答