+ Start a Discussion
Jayaramu T 9Jayaramu T 9 

in below code at line number 8. i am getting "Too many SOQL 101" error while running my test class. can any one please suggest me on this?

public static void onAfterUpdate(Case[] oldRecords, Case[] updatedRecords, Map<ID, Case> oldRecordMap)
  {
    autoAssignCase(updatedRecords);
    // Take new cases, bulkified
    LIST<Case> caselist = Trigger.new;
    // Find all Custom Settings defining default Case Milestones
    LIST<CaseMilestoneSetting__c> CMileSs = [select ID, CaseCriteria__c, MilestoneID__c from CaseMilestoneSetting__C];
    // Loop through each Custom Setting for Case Milestones
    //Fixed LOOp Standard case settings
    Set<Id> mstoneID = new Set<Id>();
      String alias;
      List<CaseMilestone> setmstones ;
    List<CaseMilestone> lp_setmstones = new List<CaseMilestone>();
    for (CaseMilestoneSetting__c CMileS : CMileSs){
        mstoneID.add(CMileS.MilestoneID__c);
        if(CMileS.CaseCriteria__c != null){
            alias = CMileS.CaseCriteria__c;
        }
    }
      
       if(system.test.isRunningTest())
            setmstones = Database.query('Select ID,MilestoneTypeID,CompletionDate FROM CaseMilestone WHERE CaseID IN:caselist AND MilestoneTypeID=:mstoneID AND CompletionDate=NULL');
else
   setmstones = Database.query('Select ID,MilestoneTypeID,CompletionDate FROM CaseMilestone WHERE '+      alias+   'AND CaseID IN:caselist AND MilestoneTypeID=:mstoneID AND CompletionDate=NULL');
                                                      
        // Update the CompletionDate for each CaseMilesone
        for (CaseMilestone updatemstone : setmstones){
            updatemstone.CompletionDate= Datetime.now();
        }
        // Execute the update for all the Milestones in this set
        lp_setmstones.addAll(setmstones);
  
    if(lp_setmstones.size()>0)
    {
        // Execute the update for all the Milestones in this set
        update lp_setmstones;
    }
    Map<ID,Case> installCases = new Map<ID,Case>();
    ID InstallID;
    List<RecordType> installTypes = [SELECT ID, DeveloperName FROM RecordType WHERE sObjectType='Case' AND DeveloperName='Installation_Report' LIMIT 1];
    if(installTypes.size()>0){
        InstallID=installTypes[0].Id;
    }
    for(Case c : updatedRecords){
        if(c.IsClosed && !oldRecordMap.get(c.id).IsClosed && c.RecordTypeID==InstallID && c.AssetId!=null &&c.Status!='Closed As Duplicate'){
            installCases.put(c.AssetId,c);
        }
    }
    Asset_Util.UpdateAssetInstall(installCases);
    //Porcess Builder - Case - update asset fields
    updateAssetFields(updatedRecords);
  }
Test class
---------------------------------
@istest
private class RPUDashboardBatchTest{
  @testSetup static void setup(){
 
      Integer pastYear = Date.today().addYears(-2).year();
      Date pastDate = Date.newInstance(pastYear, 01, 01);
      Date currentDate =Date.today();
      String blankVal ='';
 
      Product2 pro= new Product2();
      pro.Product_Group__c='Consumer Products';
      pro.Product_Collection__c='3D Printers';
      pro.Product_Category__c='CubeX';
      pro.Name='Common34';
      insert pro;
 
    
      Asset[] assetRecList= new List<Asset>();
     
     
          
       Integer currYear = Date.today().year();   
       for (Integer z=Date.today().addYears(-2).year();z<=Date.today().year();z++) {
           Asset ast;
           for (Integer assetMonth=1; assetMonth<=12;assetMonth++){
                ast=new Asset();          
                ast.Name='Assettest';
                ast.Ship_Date__c = date.newInstance(z, assetMonth+1, 1);
                if((assetMonth <= Date.today().month() && z==Date.today().year()) || (z < Date.today().year()))
                ast.InstallDate=date.newInstance(z, assetMonth, 1);
                ast.Product2Id = pro.Id;
              
                System.debug('@@ShipYear'+ast.Ship_Date__c);
                System.debug('@@assetMonth'+ast.InstallDate);
                assetRecList.add(ast);
            }
       }
      
     
       insert assetRecList;
     
       Asset as1= new Asset();
            as1.Name='Assettest';
            as1.Ship_Date__c = date.newInstance(2016, 1, 1);
            as1.InstallDate=date.newInstance(2016, 1, 1);
            as1.Product2Id = pro.Id;
          
            insert as1;
     
      List<Asset> lsAsset = [select id, Product_Group__c, Product_Collection__c, Product_Category__c from Asset where id IN:assetRecList];
      System.debug('@@lsAsset'+lsAsset);
    
      Integer assetCount= [select count() from Asset where id IN: assetRecList];
      //System.assertEquals(3, assetCount);
      Asset j=assetRecList[0];
       id u=j.id;
    
    
      Issue__c iss=new Issue__c();
      iss.Name='Issuename1';
      iss.Active__c=True;    
      iss.Product_Group__c='Consumer Products';
      iss.Product_Collection__c='3D Printers';
      insert iss;
    
      List<RecordType> i=[Select id,Name from RecordType where Name =:'SalesForce Support'];
      Id k;
   
      RecordType p=i[0];
      k=p.id;
   
    
   //Marwin Change: Validation Rule of Contact_Cannot_Equal_Case_Creator, a case must not have a recordId of 01280000000GFJM"Installation Report"
      Id InstReport = [Select id from RecordType where SobjectType = 'Case' and Name =:'Installation Report' limit 1].id;    
     Case[] CaseList= new List<Case>();
     Integer assetIndex =0;
      for (Integer x=Date.today().addYears(-2).year();x<=Date.today().year();x++) {
            Case cs;
            for (Integer CaseMonth=1; CaseMonth<=12;CaseMonth++){
                cs =new Case();
                cs.RecordTypeId = InstReport ; //change from InstReport to k
                cs.bypassvalidation__c = true;
                cs.Status='Open';
                cs.Description='testdescription';       
                cs.AssetID=assetRecList[assetIndex].Id;
                if((CaseMonth <= Date.today().month() && x==Date.today().year()) || (x < Date.today().year()))
                cs.Install_Completion_Date__c=date.newInstance(x, CaseMonth, 1);
                CaseList.add(cs);
                system.debug('***CaseInstallDate***'+cs.Install_Completion_Date__c);
                assetIndex++;
            }
          
      }
      system.debug('***CaseList***'+CaseList);
      insert CaseList;
    
      Case[] CaseList2= new List<Case>();
    
            for (Integer MonthCounter=1; MonthCounter<=12;MonthCounter++){
                Case cs =new Case();
                cs.RecordTypeId= k ;
                cs.Status='Open';
                cs.Description='testdescription';
                cs.AssetID=assetRecList[MonthCounter-1].Id;
                CaseList2.add(cs);
            }
          
    
      system.debug('***CaseList2***'+CaseList2);
      insert CaseList2;
    
      Case_Issue__c[] CaseIssueList= new List<Case_Issue__c>();
      Integer casecount=0;
      for (Integer y=Date.today().addYears(-2).year();y<=Date.today().year();y++) {
            Case_Issue__c csiss;
            for (Integer MonthCount=1; MonthCount<=12;MonthCount++){
                if((MonthCount <= Date.today().month() && y==Date.today().year()) || (y < Date.today().year())){
                    csiss =new Case_Issue__c();
                    csiss.Case__c = CaseList[casecount].id;
                    csiss.Issue__c= iss.id;
                    csiss.Product_Group__c='Consumer Products';
                    csiss.Product_Collection__c='3D Printers';
                    //Integer installedYear = csiss.asset.InstallDate.year();
                    casecount++;
                    CaseIssueList.add(csiss);
                }
            }
          
      }
      system.debug('***CaseIssueList***'+CaseIssueList);
      insert CaseIssueList;
    
    
      RPU_OOB_Dashboard_Settings__c custSettings = new RPU_OOB_Dashboard_Settings__c();
      custSettings.Name = 'RPUBatchRunTime';
      custSettings.Dashboard_Run_Date__c = system.now();
      custSettings.Status__c = 'Incomplete';
      insert custSettings;
    
    }
  
    public static testmethod void rputest(){
  
  
    test.starttest();
    setup();
    RPUDashboardBatch rs=new RPUDashboardBatch();
    rs.currentDate=date.newInstance(Date.today().year()+1, 1, 1);
    Database.executebatch(rs,200);
    test.stoptest();
  
  
    }
  
    static testMethod void createData(){
    test.starttest();
  
    Account  act = new Account(Name= RPUDashboardBatch.generateRandomString() +'_' +'test', BillingCountryCode='KR');
    insert act;
     Product2 product2_1 = new Product2(
          Name = 'NFR - Freeform Plus',
          CanUseRevenueSchedule = false,
          IsActive = true,
          CurrencyIsoCode = 'USD',
          fw2__Non_Installment__c = false,
          fw2__Recurring__c = false,
          Published__c = true,
          IsFlex__c = true,
          Asset_Tracking__c = false,
          ERP_Taxable_Flag__c = false,
          Servicing_Only__c = false,
          IsEDU__c = false,
          ERP_COMS_NL_TRACKABLE__c = false,
          Asset_Tracking_Override__c = false,
          CPQNewSale__c = false,
          Product_Collection__c ='Geomagic'
        );
        insert product2_1;
    Asset ass = new Asset(Name= RPUDashboardBatch.generateRandomString() +'_' +'test', AccountId=act.id,Product2ID=product2_1.ID);
     insert ass;
     Reseller__c resell2 = new Reseller__c(Name='non-user test',Account__c=act.id);
     insert resell2;
     Opportunity opp = new Opportunity(Name= RPUDashboardBatch.generateRandomString() +'_' +'test-op',AccountID=act.ID,Rapidform_Reseller__c=resell2.ID,StageName='Qualified',CloseDate=Date.today(),FlexNetID__c='12345');
     insert opp;
     test.stoptest();
     }
   }
Khan AnasKhan Anas (Salesforce Developers) 
Hi Jayaramu,

Greetings to you!

The following error appears when you exceed the Execution Governors Limit (you can run up to a total 100 SOQL queries in a single call or context): https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

To fix the issue, change your code so that the number of SOQL fired is less than 100.
If you need to change the context, you can use @future annotation which will run the code asynchronously.
 
Best practices to avoid exceeding the Governors Limit:

Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure code doesn't monopolize shared resources.
 
Reference: https://help.salesforce.com/articleView?id=000181404&type=1

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Jayaramu T 9Jayaramu T 9
Thanks Khan 

but in my case i don't find any SOQL or DML inside for loops and i follows the best practice still i  am getting that 101 error i am totally confused why it is .