function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Trif Cristian 7Trif Cristian 7 

I don't understand how methods Start.TestStart() and Stop.TestStart() works, please help

So the following task is this:

User-added image

And I have the following class in which I have to write my Test.StartTest() and Test.StopTest(). I don't know how to connect the dots, I really don't know how these methods Test.StartTest() and Test.StopTest() works, as I'm new to Salesforce.

@isTest 
public with sharing class AccountDealerSignSelectControllerTest {
    
    @testSetup 
    private static void setupTestData() {
        
        TestUtil.insertBaseData(1);
        
        User userStandard = TestUtil.getUserStandardDE(0);
        
        System.runAs(userStandard) {
            Account dealerAccount = new Account(    Name                            = 'Dealer Test', 
                                                    RecordTypeId                    = SystemUtil.getRecordTypes(Account.SObjectType).get(Label.RECORDTYPE_ACCOUNT_ACCOUNTBUSINESSINTERNAL_DEVNAME).getRecordTypeId(), 
                                                    SourceSystem__c                    = Label.GLOBAL_PICKLIST_SOURCESYSTEM_RSPCRM_VALUE, 
                                                    CustomerMainType__c                = Label.ACCOUNT_PICKLIST_CUSTOMER_MAINTYPE_DEALER_VALUE, 
                                                    CustomerType__c                    = Label.ACCOUNT_PICKLIST_CUSTOMERTYPE_SPECIAL_VALUE, 
                                                    CustomerSubType__c                = Label.ACCOUNT_PICKLIST_CUSTOMER_SUBTYPE_OTHER_VALUE,
                                                    BusinessAddressCountry__c       = 'DE',
                                                    BusinessAddressPostalCode__c    = '10000',
                                                    BusinessAddressCity__c          = 'TestCity',
                                                    BusinessAddressStreet__c        = 'TestStreet',
                                                    BusinessAddressStreetNumber__c  = '1');
            insert dealerAccount;
        }
    }
    
    static testMethod void signatureSelection1Test() {
        
        User userStandard = TestUtil.getUserStandardDE(0);
        
        System.runAs(userStandard) {
            
            Account dealerAccount = [SELECT Id FROM Account WHERE Name = 'Dealer Test'];
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertNotEquals(null, dealerAccount);
            }
            Attachment att = new Attachment(Name='Test Att', ParentId=dealerAccount.Id, Body=Blob.valueOf('Test Body String') );
            insert att;
            
            ApexPages.CurrentPage().getParameters().put('id', dealerAccount.Id);
            AccountDealerSignatureSelectController controller = new AccountDealerSignatureSelectController();
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertNotEquals(null, controller);
            }
            controller.isSignature1 = true;
            controller.selectedAttachmentId = att.Id;

            controller.selectSignature();
            Account dealerAccountFromDB = [SELECT SignatureAuthorization1__c FROM Account WHERE Id = :dealerAccount.Id];
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertEquals(att.Id, controller.selectedAttachmentId, dealerAccountFromDB.SignatureAuthorization1__c);
                system.assertEquals(controller.currentSignatureId, dealerAccountFromDB.SignatureAuthorization1__c);
            }
            controller.deselectSignature();
            dealerAccountFromDB = [SELECT SignatureAuthorization1__c FROM Account WHERE Id = :dealerAccount.Id];
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertEquals(null, dealerAccountFromDB.SignatureAuthorization1__c);
            }
        }
    }
    
    static testMethod void signatureSelection2Test() {
        
        User userStandard = TestUtil.getUserStandardDE(0);
        
        System.runAs(userStandard) {
            
            Account dealerAccount = [SELECT Id FROM Account WHERE Name = 'Dealer Test'];
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertNotEquals(null, dealerAccount);
            }
            Attachment att = new Attachment(Name='Test Att', ParentId=dealerAccount.Id, Body=Blob.valueOf('Test Body String') );
            insert att;
            
            ApexPages.CurrentPage().getParameters().put('id', dealerAccount.Id);
            AccountDealerSignatureSelectController controller = new AccountDealerSignatureSelectController();
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertNotEquals(null, controller);
            }
            controller.isSignature1 = false;
            controller.selectedAttachmentId = att.Id;

            controller.selectSignature();
            Account dealerAccountFromDB = [SELECT SignatureAuthorization2__c FROM Account WHERE Id = :dealerAccount.Id];
            
            if (!UserUtil.IsDisabledTestClassesAssert) {
                
                system.assertEquals(att.Id, controller.selectedAttachmentId, dealerAccountFromDB.SignatureAuthorization2__c);
                system.assertEquals(controller.currentSignatureId, dealerAccountFromDB.SignatureAuthorization2__c);
            
                controller.deselectSignature();
                dealerAccountFromDB = [SELECT SignatureAuthorization2__c FROM Account WHERE Id = :dealerAccount.Id];
                system.assertEquals(null, dealerAccountFromDB.SignatureAuthorization2__c);
            }
            
        }
    }
}
Sohan Raj GuptaSohan Raj Gupta
Hi Trif,

The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining.

There are two versions of every method: the first returns the amount of the resource that has been used in the current context, while the second version contains the word “limit” and returns the total amount of the resource that is available for that context. For example, getCallouts returns the number of callouts to an external service that have already been processed in the current context, while getLimitCallouts returns the total number of callouts available in the given context.

In addition to the Limits methods, use the startTest and stopTest methods to validate how close the code is to reaching governor limits.

The startTest method marks the point in your test code when your test actually begins. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need to run your test. Any code that executes after the call to startTest and before stopTest is assigned a new set of governor limits.

The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement, the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the original context, and can only make 2 additional SOQL queries before reaching the limit of 100.

The stopTest method marks the point in your test code when your test ends. Use this method in conjunction with the startTest method. Each test method is allowed to call this method only once. Any code that executes after the stopTestmethod is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

Ref: https://developer.salesforce.com/forums/?id=906F0000000AwXlIAK

Test.startTest() and Test.stopTest() exist primarily to allow you to reset the governor limits within the context of your test execution and to be able to test asynchronous methods. These two statements cannot be called more than once within a testMethod. They are not required to be used but in some situations may be critical. Asynchronous (@future) calls made during the test are also finalized when you call Test.stopTest() allowing you to test the results of asynchronous behavior in your code.
Given a scenario where you need to execute numerous queries and a large number of DML rows in order to set up the data for the actual code being tested, it might be impossible for you to run your test without these statements.
For instance in this fictional scenario, if during the setup of your test you needed to execute 99 SOQL queries and insert 9,999 records to seed the org with the data your code required for proper testing, if Salesforce did not offer a mechanism to reset the governor limits the code which you are testing would only have room for one more SOQL query and one more record in a DML statement before it would hit one of those two limits (100 queries and 10,000 records processed by DML statements respectively) and throw an exception.
In the above scenario, if you were to call Test.startTest() after your 99 queries were complete and your 9,999 rows were DML'd - the transaction limits within your test would be back to zero and at that point the code which you are testing would be running in a context that more closely resembles a single transaction's limits in real life. This mechanism allows you to "ignore" the work that had to be done to set up the test scenario.

Ref: https://salesforce.stackexchange.com/questions/80949/when-to-use-test-starttest


If you like this, please select as best answer.

Thank You
Sohan Raj Gupta
Trif Cristian 7Trif Cristian 7
Thank you for the answer, Gupta.
But in my case where, in that class i have where should I write my methods, the Test.StartTest() and Test.StopTest() ? 
I wrote it like this: 
static testMethod void signatureSelection1Test() {
        Test.StartTest();
        User userStandard = TestUtil.getUserStandardDE(0);
        Test.StopTest();
I don't have any errors or something but I'm not sure where to write these methods in my class.
Sohan Raj GuptaSohan Raj Gupta
Hi Trif,

In your code you are using classes TestUtil and AccountDealerSignatureSelectController, so first you need count how many DML and SOQL query is running in below function:

TestUtil.getUserStandardDE(0);
controller.selectSignature();
controller.deselectSignature();

As per governor limits you can use only 150 DML and 100 SOQL statementes in one transaction. So, check your test call code and if your code exceed governor limits then you should use Test.startTest() and Test.stopTest() method.

Suppose, signatureSelection1Test() method is using 155 DML statements, like:

TestUtil.getUserStandardDE(0) = 25 DML
controller.selectSignature() = 75 DML
controller.deselectSignature() = 75 DML

In this case you need to use
Test.startTest();
controller.deselectSignature();
Test.stopTest();

I hope this will help you now.

Thank you,
Sohan Raj Gupta
Trif Cristian 7Trif Cristian 7
Thank you again for your answer. I'm getting a little bit clearer on this but still I have two more questions:
1. How can I run those DML and SQOL statements and see if I exceed those limitations? How can I check myself?
2. What exactly is the TestUtil and what is controller.selectSignature() and controller.deselectSignature() are those methods which returns some DML ? so selectSignature() and deselectSignature() are the methods and controller is the class??
Sohan Raj GuptaSohan Raj Gupta
Hi Trif,

Check reply on your below questions:
1) No need to run, you just open these classes function and try to count all DML and SOQL statements are written.
2) TestUtil and AccountDealerSignatureSelectController are classes which are used in your test class.  selectSignature() and deselectSignature() are the functions of AccountDealerSignatureSelectController class.

Test.startTest() and Test.stopTest() methods can use only one time per transaction.

Suppose, in your test class below methods took respective DML statements: 
TestUtil.getUserStandardDE(0) = 25 DML
controller.selectSignature() = 75 DML
controller.deselectSignature() = 75 DML

In this case total DML statement is 175, so it is exceeding governor limits. So I will write below code then it will consider 100 DML statements only and 75 DMl for Test.startTest() methods.
Test.startTest();
controller.deselectSignature();
Test.stopTest();

If we write some code between Test.startTest() and Test.stopTest() methods then it governor limit from 1. Suppose if we write 75 DML statements befor Test.startTest() method, 75 DML between Test.startTest() method and 50 DML after Test.stopTest() method, then it will count 125 DML statements.