Salesforce APEX简单触发器的测试类别

问题描述 投票:0回答:2

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

}

}
triggers salesforce apex apex-code
2个回答
0
投票

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

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

让我知道您是否需要更多帮助。


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;
© www.soinside.com 2019 - 2024. All rights reserved.