用于简单触发器的Salesforce APEX测试类

时间:2019-01-31 02:18:34

标签: triggers salesforce apex apex-code

我对此一直发疯。我的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;

}

}

2 个答案:

答案 0 :(得分:0)

我认为您可以将主要逻辑复制到apex类,并从apex触发器调用apex类的方法。

因此,这将使编写测试类更加容易。

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

答案 1 :(得分:0)

我确定您现在已经弄清楚了,但是此代码块正在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;