The Test.startTest() does not reset the number of SOQL queries
Last updated 2022-02-10 ·Reference W-2354529 ·Reported By 62 users
Summary
The number of SOQL queries could not be reset after the Test.startTest() call. So any SOQL query executed after the call to startTest() and before stopTest() could hit the governor limit and fail with the System.LimitException.
Repro
Run the following Apex test class.
@Istest public class testSOQLQueryLimits {
static testmethod void doTest() {
insert new Account(name = 'mytest');
Integer MAX_QUERY = Limits.getLimitQueries();
Integer NUM_QUERY = MAX_QUERY - 1;
for (Integer i = 0; i < NUM_QUERY; i++) {
Account a = [select id from account limit 1];
}
System.assertEquals(NUM_QUERY, Limits.getQueries());
Test.startTest();
for (Integer i = 0; i < NUM_QUERY; i++) {
Account a = [select id from account limit 1];
}
System.assertEquals(NUM_QUERY, Limits.getQueries());
Test.stopTest();
System.assertEquals(NUM_QUERY, Limits.getQueries());
}
}
After calling the Test.startTest() method, you would expect that the number of queries get reset.
But the execution fails with "System.LimitException: Too many SOQL queries: 101" at line#16.
Workaround
WORKAROUND:
Call a user defined method just after the Test.startMethod() call. It creates a new LimitsAndVals for a test.
following test runs fine
@Istest public class testSOQLQueryLimits {
static testmethod void doTest() {
insert new Account(name = 'mytest');
Integer MAX_QUERY = Limits.getLimitQueries();
Integer NUM_QUERY = MAX_QUERY - 1;
for (Integer i = 0; i < NUM_QUERY; i++) {
Account a = [select id from account limit 1];
}
System.assertEquals(NUM_QUERY, Limits.getQueries());
Test.startTest();
System.assertEquals(NUM_QUERY, Limits.getQueries());
for (Integer i = 0; i < NUM_QUERY; i++) {
Account a = [select id from account limit 1];
}
System.assertEquals(NUM_QUERY, Limits.getQueries());
Test.stopTest();
System.assertEquals(NUM_QUERY, Limits.getQueries());
}
}
Reported By (62)























Is it Fixed?
Any unreleased services, features, statuses, or dates referenced in this or other public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make their purchase decisions based upon features that are currently available.