2012-07-26 37 views
1

我已經編寫了Saleforce觸發器的測試。每當'Account_Status__c'更改時,觸發器將Account_Status_Change_Date__c值更改爲當前日期。Salesforce測試失敗,但在系統上工作

我已通過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(); 
     } 
    } 
} 

回答

3

你並不需要一個觸發器來做到這一點。這可以通過賬戶上的簡單工作流規則來完成。但是,測試代碼的問題在於,您需要在更新後查詢帳戶以獲取帳戶字段中的更新值。

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); 
} 
+0

非常感謝。這很好:)所以,爲了確認,我的測試代碼中的acc變量保存在內存中,但實際的觸發器只更新數據庫,所以我需要重新選擇才能將更新值更新爲' acc'可變內存。對? – Joe 2012-07-26 16:20:28

+1

準確地說,Sobjects以與其他對象相同的方式存儲在內存中,因此數據庫中的更改不會傳播回給它們,除非您查詢已更改的數據。 – 2012-07-26 16:23:29

+0

再次感謝:) – Joe 2012-07-26 16:25:20

相關問題