编写货币转换触发器的测试类

时间:2018-01-25 21:55:39

标签: triggers salesforce apex test-class

我在为此触发器编写测试类时几乎没有帮助,该测试类将记录货币转换为组织货币。有人可以协助/指导吗?请。

trigger convertToEuro on CustomObject(before update) { 

List<CurrencyType> currencyTypeList = [select id,IsoCode,ConversionRate from CurrencyType where isActive = true] ;

Map<String , Decimal> isoWithRateMap = new Map<String, Decimal>();

for(CurrencyType c : currencyTypeList) {

    isoWithRateMap.put(c.IsoCode , c.ConversionRate) ;

}

for(CustomObject ce: trigger.new){

    if(ce.CurrencyIsoCode != 'EUR' && isoWithRateMap.containsKey(ce.CurrencyIsoCode)){

        ce.Amount_Converted__c = ce.ffps_iv__Amount__c/ isoWithRateMap.get(ce.CurrencyIsoCode);

    }

}

}

1 个答案:

答案 0 :(得分:0)

@isTest(seealldata=false)
public class testConvertToEuro{
   @testSetup
   static void setupTest(){
       List<CurrencyType> liCT = New List<CurrencyType>();
       List<CustomObject> liCO = New List<CustomObject>();
       Integer iCounter = 0;
       liCT.add(new CurrencyType(IsoCode='EUR',ConversionRate=1,isActive=TRUE));
       liCT.add(new CurrencyType(IsoCode='USD',ConversionRate=2,isActive=TRUE));
       liCT.add(new CurrencyType(IsoCode='XXX',ConversionRate=3,isActive=TRUE));
       liCT.add(new CurrencyType(IsoCode='YYY',ConversionRate=4,isActive=TRUE));
       liCT.add(new CurrencyType(IsoCode='ZZZ',ConversionRate=5,isActive=TRUE));
       for(Integer i=0; i<251; i++){
            CustomObject co = New CustomObject(
               CurrencyIsoCode = liCT[iCounter].IsoCode;
               ffps_iv__Amount__c = liCT[iCounter].ConversionRate + .01;
            );

           if(iCounter < liCT.size() -1){
               iCounter += 1;
           }
           else{
               iCounter = 0;
           }
        }
       insert liCT;
       insert liCO;
   }
   static testmethod void runTest(){
       setupTest();
       List<CustomObject> liCustomObjectsToUpdate = New List<CustomObject>();
       for(CustomObject co : [SELECT Id, ffps_iv__Amount__c, Amount_Converted__c from CustomObject]){
           co.ffps_iv__Amount__c -= .01;
           liCustomObjectsToUpdate.add(co);
       }
       test.startTest();
       Update liCustomObjectsToUpdate;
       test.stopTest();
       System.assertEquals([SELECT Id, Amount_Converted__c FROM CustomObject LIMIT 1][0].Amount_Converted__c, 1);
   }
}   

我无法在不添加自定义对象的情况下测试此代码,因此可能会出现一些错误。请告诉我你得到的错误。如果您需要帮助调试,您应该提供正在使用的确切代码和确切的错误消息。

它遵循测试更新触发器的基本模式:

  1. 插入测试数据
  2. 检索测试数据
  3. 更新记录
  4. 断言触发器生成了所需的结果