在一个测试方法中不能调用超过一个 executeBatch

No more than one executeBatch can be called from within a testmethod

如何修复测试中的以下错误消息class

            System.UnexpectedException: No more than one executeBatch can be called from within a test method.  Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

请注意,已按照此处的建议尝试添加 Limit 200 https://help.salesforce.com/articleView?id=000330685&type=1&mode=1,但没有成功

我的顶点class是

            global class ERTExtract255BatchClass implements Database.Batchable<sObject> {
                global Database.QueryLocator start(Database.BatchableContext bc) {
                    return Database.getQueryLocator(
                'SELECT ID,Description,Case_Desc_255__c FROM Case' 
                    );
                }
                global void execute(Database.BatchableContext bc, List<Case> scope){
                // process each batch of record
                List<Case> lstCase = new List<Case>();       
                for (Case cas : scope) {
                string Strdesc = cas.Description ; 
            if(Strdesc.length()>255){
                cas.Case_Desc_255__c = cas.Description.Left(255);
                lstCase.add(cas);  
            }
                }   
            update lstCase;
            }   
            global void finish(Database.BatchableContext bc){

            }   
 
            }

我的测试class是

            @isTest(SeeAllData=false)
            public class testERTExtract255BatchClass {

            @IsTest
            static void testBatchJob(){
              
               List<Case> cases = new List<Case>();
               for (integer i =0;i<300;i++)
               {
                    Case c = new Case();
                    c.Description = 'aaaaaa'.rightPad(255,'b');
                    c.status = 'new';
                    c.Subject = 'test';
                    //add other mandatory fields 
                    cases.add(c);
                }

                insert cases;

                Test.startTest();
                Database.executeBatch(new ERTExtract255BatchClass());
                Test.stopTest();


                Case Strcase = [Select id,Case_Desc_255__c from Case];
                System.assertEquals(Strcase.Case_Desc_255__c.length(),255);

                    }
            }

您需要 for (integer i =0;i<300;i++) 的任何特殊原因? 如果你赚了 200 或更少,它应该很好地适合“单元测试中的 1 次 execute() 调用”。

或者您可以将可选参数传递给 Database.executeBatch 方法。 (在该文档中,您可以看到默认值为 200)。所以如果你去 Database.executeBatch(new ERTExtract255BatchClass(), cases.size()); 应该没问题。