Test Class 在運行過程中眨补,有時會碰到 Query 101的 Error, 這篇文章會提醒我們在代碼過程中需要規(guī)避的問題以及碰到這種問題的時候的解決方案。
Here are some tips that will improve your code and boost your stock on the Salesforce job market!
Avoid using Seealldata=true if possible. It's better to just create these records from scratch in your Test Class. This is not only a good Salesforce practice, but also a good coding practice in general. Plus, you'll save on SOQL queries.(盡量避免使用 seeAlldata = ture, 這個基本屬于嚴(yán)禁使用的)
Combine your SOQL queries - for example, you could have done this instead:
List<RecordType> recordTypes = [SELECT Id FROM RecordType WHERE Name IN ('Commercial Deal Sheet', 'Residential Rental Deal Sheet', 'Residential Sale Deal Sheet', 'Referral Deal Sheet')];
(對你的Query 語句來說翔始,最好拼接你的SOQL罗心,不要每條單獨查詢)Combine your DML statements by using update on a list instead of individual records. All SOQL queries from your triggers will fire with each update statement, which is causing you to hit your limit. It looks like in this case you might need to use each update call, so check out tip #4(在準(zhǔn)備測試數(shù)據(jù)的過程中,要盡量使用LIst來進行DML操作绽昏,不要對單獨對每條數(shù)據(jù)進行操作)
- Separate your test class into multiple test classes. This is the easiest way to get by governor limits in test classes - just split your test class in half and make it into two separate test classes. You'll get double the governor limits!(如果還是在單個文件中達(dá)到了 salesforce Limitation协屡,可以把一個測試類分成多個)
5. Use Test.startTest() and Test.stopTest(). You can do all your queries in the beginning of your class, then do all your updates inside Test.startTest() and Test.stopTest(). You get a fresh set of governor limits inside these too!(Test.startTest() 和 Test.stopTest() 方法之間的LImit是單獨計算的,所以可以在測試方法中加入這兩個方法來規(guī)避Limitation)
- 還有一個方法可以規(guī)避101 Error, 就是在setup 方法里面加入 Test.startTest() 和 Test.stopTest() 方法全谤,如下:
/*
* Avoid SOQL 101 error
*/
Test.startTest();
System.runAs(loggedInUser){
OpportunityLineItem opl = TestDataFactory.createOpportunityLineItem(oppty);
opl.Product_Network_Node__c = '1974711';
opl.Fee_Arrangement__c = '12667269';
insert opl;
}
Test.stopTest();
"Any code that executes after the call to startTest and before stopTest is assigned a new set of governor limits."
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_test.htm