You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Salesforce自定义numberRecords方法测试异常,请求排查问题

问题排查与修复方案

核心错误点

  • 测试数据未持久化:创建了Month_Expense_Application__c对象实例,但未执行insert语句将其存入Salesforce数据库,导致后续SOQL查询返回空列表,调用numbersOfRecords[0]时会触发List index out of bounds异常。
  • 未调用目标测试方法:测试代码自行复刻了numberRecords的逻辑,却完全没有调用你要测试的ExpenseAdminController.numberRecords(year)方法,相当于没有对目标业务方法做任何验证。
  • 硬编码ID无效:直接写死Keeper__c = '0034x00001K7kGCAAZ',测试环境中该ID对应的记录大概率不存在,会导致测试数据无效,同时违反测试数据隔离原则。

修正后的测试类代码

@isTest
public class ExpenseAdminControllerTests {
    @isTest
    public static void numberRecordsTests() {
        // 1. 创建并插入测试用的Keeper记录(假设Keeper__c是User的lookup字段,可根据实际对象调整)
        User testUser = new User(
            FirstName = 'Test',
            LastName = 'User',
            Email = 'testuser@example.com',
            Username = 'testuser@example.com',
            ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id,
            IsActive = true,
            Alias = 'testu',
            TimeZoneSidKey = 'America/Los_Angeles',
            LocaleSidKey = 'en_US',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US'
        );
        insert testUser;

        // 2. 创建并插入费用申请测试数据
        Month_Expense_Application__c monthExpenseTest = new Month_Expense_Application__c(
            Balance__c = 12.3,
            Income__c = 11,
            Keeper__c = testUser.Id, // 使用刚创建的测试用户ID
            MonthDate__c = Date.newInstance(2022, 11, 21)
        );
        insert monthExpenseTest;

        // 3. 调用要测试的目标方法
        Integer result = ExpenseAdminController.numberRecords(2022);

        // 4. 断言结果符合预期
        System.assertEquals(1, result, '2022年的唯一Keeper数量应为1');
    }
}

业务方法优化建议

原numberRecords方法通过遍历记录去重的方式效率较低,可直接用SOQL聚合函数优化:

public static Integer numberRecords(Integer year) {
    AggregateResult result = [
        SELECT COUNT_DISTINCT(Keeper__c) AS uniqueKeepers
        FROM Month_Expense_Application__c
        WHERE CALENDAR_YEAR(MonthDate__c) = :year
    ];
    return (Integer)result.get('uniqueKeepers');
}

内容的提问来源于stack exchange,提问作者Jhony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:55:30