Apex StartTest() & StopTest()

R

Why do we use StartTest() and StopTest()?

In Apex test classes, we often prepare test data that will later be used by the main logic.

When we insert or update this test data, it already consumes some governor limits (like DML and SOQL).

If we immediately run our main logic afterward, those consumed limits are carried forward, which doesn't make sense, we want to test our business logic fresh

That’s where Test.startTest() and Test.stopTest() come in.


Real World Example

Imagine you need to buy 10 kg of potatoes 🥔.
You place them on the weighing machine in a basket that weighs 500 grams.
The scale shows 10.5 kg, which includes both the potatoes and the basket.

To get the correct potato weight, you first reset the scale to zero with just the basket, then add the potatoes.
Now the reading shows the true weight.

That’s exactly what Test.startTest() and Test.stopTest() do they reset the “scale” (governor limits) before running the main logic, so we measure only the code we want to test.


Apex Code Example

@isTest
private class StartStopTestExample {

    static void testStartAndStopMethods() {

        // Step 1 : Create some test data
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        // Step 2 : Start the test section
        // This resets all governor limits, like starting with a clean slate.
        Test.startTest();

        // Main logic you want to test
        // (Example: updating the Account)
        acc.Name = 'Updated Account';
        update acc;

        // Step 3 : Stop the test section
        // This ends the fresh governor limit context.
        Test.stopTest();

        // Step 4 : Verify the result
        Account updatedAcc = [SELECT Name FROM Account WHERE Id = :acc.Id];
        System.assertEquals('Updated Account', updatedAcc.Name, 'Account name should be updated');
    }
}