Apex新手求助:批量类测试类报List无行赋值SObject异常与覆盖率问题
批量Apex测试类问题分析与修复
错误原因解析
1. "List has no rows for assignment to SObject" 异常
测试类中直接使用单条SObject赋值的SOQL查询(例如Account acc = [SELECT Id FROM Account];),但测试环境默认无测试数据,该查询返回空列表,赋值给单个Account对象时就会抛出此异常。
2. Execute方法未被覆盖
- 测试类未插入任何Account测试数据,批量类的
start方法查询不到数据,无法进入Execute逻辑。 - 可能未正确调用批量类的执行方法(如
Database.executeBatch(new BatchApexOnAccount());)。
修正后的测试类代码
@isTest private class BatchApexOnAccountTest { @isTest static void testBatchExecution() { // 插入测试用Account数据 List<Account> testAccounts = new List<Account>(); for(Integer i = 0; i < 5; i++){ testAccounts.add(new Account(Name='Test Account ' + i)); } insert testAccounts; // 执行批量类,强制完成异步操作 Test.startTest(); Database.executeBatch(new BatchApexOnAccount()); Test.stopTest(); // 验证数据更新结果 List<Account> updatedAccounts = [SELECT Id, Name, Description FROM Account]; for(Account acc : updatedAccounts){ System.assertEquals('Salesforce', acc.Name); System.assertEquals('Update Account ' + System.today(), acc.Description); } } }
核心修复要点
- 提前插入测试数据:执行批量类前必须插入符合查询条件的Account记录,确保
start方法能返回数据,触发Execute逻辑。 - 使用Test.startTest()/Test.stopTest():这两个方法会强制完成异步操作(批量Apex属于异步),保证
Execute方法被执行,从而覆盖对应代码。 - 规避单条SObject赋值查询风险:若需查询单条记录,要么确保数据已存在,要么用列表接收后判断非空再取值,例如
List<Account> accList = [SELECT Id FROM Account]; if(!accList.isEmpty()){ Account acc = accList[0]; }
内容的提问来源于stack exchange,提问作者Yash Hatekar
相关产品推荐
相关产品推荐

