TestClass也写了很多了,遇到这个错误还是第一次,所以写篇简短的文章。
Time Started | 2022/10/06 21:37 | ||
Class | MapTCreateGitCSVBatchTest | ||
Method Name | initViewLoadTest | ||
Pass/Fail | Fail | ||
Error Message | 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. | ||
Stack Trace | External entry point |
在Test方法中,executeBatch只能被调用一次。
明白了错误内容之后,我们再来解析TestClass的代码。
下面是TestClass的代码
@isTest
public class MapTCreateGitCSVBatchTest{
@testSetup
private static void CreateTestData(){
DrawingManagerCSVList__c DrawingManagerItem = new DrawingManagerCSVList__c();
insert DrawingManagerItem;
system.debug('■DrawingManagerItem was Created------------------>'+DrawingManagerItem);
}
@isTest static void initViewLoadTest() {
DrawingManagerCSVList__c DrawingManagerItem = new DrawingManagerCSVList__c();
insert DrawingManagerItem;
system.debug('■DrawingManagerItem was Created again------------------>'+DrawingManagerItem);
MapTCreateGitCSVBatch BatchItem = new MapTCreateGitCSVBatch();
Test.startTest();
database.executeBatch(BatchItem,1);
Test.stopTest();
}
}
正如代码所述,
■在CreateTestData方法中创建了一条DrawingManagerCSVList__c数据
■在initViewLoadTest方法中又创建了一条DrawingManagerCSVList__c数据
所以在这个TestClass执行的时候,实际有两条测试数据。
更重要的一点,我们看Salesforce网站上面关于executeBatch的定义。
Use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren’t running into governor limits.
executeBatch方法中,有限定每次Batch执行的数据限制数量,当然这个数量是可以省略的,默认的数字是200。
那我们的TestClass里面指定的数量是1,这就很明显了。
在这个TestClass执行的时候,MapTCreateGitCSVBatch会被执行到两次,
如果没有No more than one executeBatch can be called from within a testmethod的限制的话。
所以问题点,就在下面的数量1。
database.executeBatch(BatchItem,1);
我把数量修改成2,再来跑一下测试类。
下面是正确的测试类
@isTest
public class MapTCreateGitCSVBatchTest{
@testSetup
private static void CreateTestData(){
DrawingManagerCSVList__c DrawingManagerItem = new DrawingManagerCSVList__c();
insert DrawingManagerItem;
system.debug('■DrawingManagerItem was Created------------------>'+DrawingManagerItem);
}
@isTest static void initViewLoadTest() {
DrawingManagerCSVList__c DrawingManagerItem = new DrawingManagerCSVList__c();
insert DrawingManagerItem;
system.debug('■DrawingManagerItem was Created again------------------>'+DrawingManagerItem);
MapTCreateGitCSVBatch BatchItem = new MapTCreateGitCSVBatch();
Test.startTest();
database.executeBatch(BatchItem,2);
Test.stopTest();
}
}
结论:
■在写测试类的时候,注意里面的数量。
database.executeBatch(BatchItem, 1 );
■@IsTest(SeeAllData=true)也尽量不要用,如果Object里面的数据都能够被查询到,那么我们的Batch在测试类里面就有可能被多次执行(就出错啦)
关于Batch的使用和注意事项可以参照下面的链接
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm
相同错误,在Salesforce官方网站上面也有,也可以参照一下
https://help.salesforce.com/s/articleView?id=000330685&type=1