ApexSensei

Drills › Prove it with tests

Reset limits around the act

Prove it with tests · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A service has a query budget, and its test setup already uses queries before the service runs.

Use Test.startTest and Test.stopTest to count only the queries the code under test runs.

What you will learn

Test.startTest() gives the code you test a fresh set of governor limits. Test.stopTest() ends that window and puts the old limits back. It also runs async work queued inside the window, such as @future or Queueable jobs, before the next line.

Test.startTest();
service.run();
Integer used = Limits.getQueries();
Test.stopTest();

Gotcha. Each test method can call startTest and stopTest only once.

The task

Finish the helper so it counts only the queries the service runs, even when setup has already used the whole query limit.

Examples:

  • setup used all 100 queries, the service runs 0 → returns 0
  • setup used all 100 queries, the service runs 7 → returns 7, with no limit error
  • no Test.startTest() → the service's first query is query 101 and the test stops

Requirements:

  1. Call Test.startTest() right before the service call.
  2. Read Limits.getQueries() after the service call and before Test.stopTest().
  3. Call Test.stopTest() before you return, so the fresh window closes.
  4. Keep measureFreshQueries public static. The checks use up the query limit first, then call it.

Starter code

@IsTest
public class AS_97398297DFBD_LimitTests {
    public static Integer measureFreshQueries(Integer count) {
        AS_97398297DFBD_QueryWork.run(count);
        Integer used = Limits.getQueries();
        return used;
    }

    @IsTest
    static void measuresWork() {
        Assert.areEqual(2, measureFreshQueries(2));
    }
}

When it passes

The helper opens a fresh limit window, counts only the service's queries, closes the window, and returns the count.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Check partial DML results · Prove bulk behavior ›