【问题标题】:Salesforce APEX Test Class for Simple Trigger用于简单触发器的 Salesforce APEX 测试类
【发布时间】:2019-06-24 10:20:27
【问题描述】:

我一直为此发疯。我的 IF 循环中没有任何内容通过我的测试类触发,我不知道为什么。我在网上做了很多阅读,看起来我做的事情是正确的,但它仍然没有解决我的代码覆盖率问题。这是运行的最后一行: 如果 (isWithin == True){
在那之后,我无法在那个 IF 循环中运行任何东西,我已经颠倒了逻辑,它仍然没有运行。我觉得当有人指出时我会踢自己,但这是我的代码:

trigger caseCreatedDurringBusinessHours on Case (after insert) {

//Create list and map for cases
List<case> casesToUpdate = new List<case>();
Map<Id, case> caseMap = new Map<Id, case>();

// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];

// Create Datetime on for now in the local timezone.
    Datetime targetTime =System.now();

// Find whether the time now is within the default business hours
Boolean isWithin;
    if ( Test.isRunningTest() ){
        Boolean isWithin = True;
    }
    else{
        Boolean isWithin = BusinessHours.isWithin(bh.id, targetTime); 
    }

// Update cases being inserted if during business hours
If (isWithin == True){

    // Add cases to map if not null
    For(case newcase : trigger.new) {
        if(newcase.id != null){
            caseMap.put(newcase.Id, newcase);
        }
    }

    // Check that cases are in the map before SOQL query and update
    If(caseMap.size() > 0){

        // Query cases
        casesToUpdate = [SELECT Id, Created_During_Business_Hours__c FROM case WHERE Id IN: caseMap.keySet()];

        // Assign new value for checkbox field
        for (case c: casesToUpdate){
                c.Created_During_Business_Hours__c = TRUE;
        }

        // if the list of cases isnt empty, update them
        if (casesToUpdate.size() > 0)
        {
            update casesToUpdate;
        }

    }


}   

}

这是我的测试课:

@isTest
private class BusinessHoursTest {

@isTest static void createCaseNotInBusinessHours() {
    case c = new case();
    c.subject = 'Test Subject';
    insert c;

}

}

【问题讨论】:

  • 为了澄清,我的测试类有 43% 的代码覆盖率,需要超过 75%

标签: triggers salesforce apex apex-code


【解决方案1】:

我认为你可以将主逻辑复制到 apex 类中,然后从 apex 触发器调用 apex 类的方法。

这样编写测试类会更容易。

如果您需要更多帮助,请告诉我。

【讨论】:

    【解决方案2】:

    我相信您现在已经弄清楚了,但是这段代码正在重新定义 if/else 块内的 isWithin 变量:

    Boolean isWithin;
    
    if (Test.isRunningTest()) {
        Boolean isWithin = True;
    } else {
        Boolean isWithin = BusinessHours.isWithin(bh.id, targetTime); 
    }
    

    必须是:

    Boolean isWithin;
    
    if (Test.isRunningTest()) {
        isWithin = True;
    } else {
        isWithin = BusinessHours.isWithin(bh.id, targetTime); 
    }
    

    或者说是最干净代码的三元运算符:

    Boolean isWithin = !Test.isRunningTest() ? BusinessHours.isWithin(bh.id, targetTime) : true;
    

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      相关资源
      最近更新 更多