1

Please let me know how to resolve the below issue.I am new to salesforce,its still giving me an error Too many DML statements: 151.Using Test.starttest() and test.stoptest() is not working.

Test Class:-

    public TestMethod static void Test_1(){
            test.startTest();
            
            id idvar;
            for(integer i=0;i<160;i++){
            account accobj=new account();
            accobj.name='TestAccount';
            accobj.CustomPhone__c='123';
            accobj.date_today__c=date.today();
            
            insert accobj;
            idvar=accobj.Id;
             }
                  
            
            test.stopTest();
            
            SampleClass sampleClObj=new SampleClass();
        } 
2
  • 1
    Your issue comes from your insert statement in the loop and SF limits. NEVER use DML statement in loop, always put all objects that need to be saved in a list and use one DML statement after the loop! Commented Jan 17, 2021 at 17:16
  • @BorisGichev Thanks for the info,i got your point. Commented Jan 18, 2021 at 15:33

1 Answer 1

6

Salesforce has a governor limits! In a single apex execution context, you can only do 150 DML operations.

Being a beginner to apex I suggest you read through some of the best practices highlighted here

Instead of doing DML in a loop, use List to collect all objects and perform one DML instead.

 @isTest
 public static void testScenario(){

    List<Account> lstaccount = new List<Account>(); // collect all records to perform DML
    id idvar;
    for(integer i=0;i<160;i++){
       account accobj=new account();
       accobj.name='TestAccount';
       accobj.CustomPhone__c='123';
       accobj.date_today__c=date.today();
      lstaccount.add(accobj);
    }
        
    insert lstaccount; // DML outside loop
        
    idvar=lstaccount[0].Id;
              
    test.startTest();
       SampleClass sampleClObj=new SampleClass();// rest of what you want to test
    test.stopTest();
  }

Also looks like you are new to Apex Testing as well! This trailhead module can help you get up to speed.

I also lately did live streaming on Trailhead, so you can watch it to learn how to create a proper test class.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .