触发器有效,但测试不能覆盖75%的代码

时间:2014-08-08 10:47:50

标签: triggers salesforce apex

我有一个可以在沙箱中使用的触发器。工作流程会检查广告系列级别中的字段,并将其与自定义设置进行比较。如果匹配,则将目标返回到DS乘数字段。触发器如下所示

trigger PopulateTarget on Campaign (before insert, before update) 
{
for(Campaign campaign : Trigger.new)
{
    if (String.isNotBlank(campaign.Apex_Calculator__c) == true)
    {
        DSTargets__c targetInstance = DSTargets__c.getInstance(campaign.Apex_Calculator__c);
        {
            String target = targetInstance .Target__c;
             campaign.DS_Target_Multiplier__c = Target;
        }
    }
}
}

但是,我在编写适当的测试时遇到了问题,并要求在互联网上提供帮助。我收到了测试

@isTest
private class testPopulateTarget{
static testMethod void testMethod1(){

      // Load the Custom Settings
      DSTargets__c testSetting = new DSTargets__c(Name='Africa - 10 Weeks; CW 10',Target__c='0.1538', SetupOwnerId = apexCalculatorUserId);
      insert testSetting;


       // Create Campaign. Since it would execute trigger, put it in start and stoptests
       Test.startTest();
           Campaign testCamp = new Campaign();
           // populate all reqd. fields.
           testCamp.Name = 'test DS campaign';
           testCamp.RecordTypeId = '012200000001b3v';
           testCamp.Started_Campaign_weeks_before_Event__c = '12 Weeks';
           testCamp.ParentId= '701g0000000EZRk';


           insert testCamp;
       Test.stopTest();
       testCamp = [Select ID,Apex_Calculator__c,DS_Target_Multiplier__c from Campaign where Id = :testCamp.Id];
       system.assertEquals(testCamp.DS_Target_Multiplier__c,testSetting.Target__c);// assert that target is populated right

}

}

此类测试返回错误“编译错误:变量不存在:第6行第122列的apexCalculatorUserId”。如果我删除了ApexCalculator部件System.assertEquals,那么测试通过。但它涵盖了代码的4/6部分(66%)

有谁可以帮助我如何修改代码以覆盖75%?

2 个答案:

答案 0 :(得分:0)

是的,尚未定义apexCalculatorUserId。您获得的代码似乎不完整。你需要查看构造函数DSTargets__c并查看它所期望的ID类型。

猜测,您可以尝试使用UserInfo.getUserId()来获取当前用户的ID,但这可能不是构造函数中预期的ID。值得一试,看看测试覆盖率是否有所提高。

答案 1 :(得分:0)

1)用UserInfo.getUserId()替换apexCalculatorUserId 2)我不确定Apex_Calculator__c在广告系列中是什么类型的字段。如果它不是一个公式,你想在&#34之前插入一个新行;插入testCamp"。就像是: testCamp.Apex_Calculator__c = UserInfo.getUserId();