首页 > 解决方案 > 用于简单触发器的 Salesforce APEX 测试类

问题描述

我一直在为这件事发疯。我的 IF 循环中没有任何内容通过我的测试类触发,我不知道为什么。我在网上做了很多阅读,看起来我做的事情是正确的,但它仍然没有解决我的代码覆盖率问题。这是运行的最后一行: 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;

}

}

标签: triggerssalesforceapexapex-code

解决方案


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

因此,它将使编写测试类变得更加容易。

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


推荐阅读