1

Hell community,

I am trying to push a class and I am getting this error: Too many SOQL queries: 101 for test class(ClonePlus_Test)

below is the class ClonePlus_Controller.

Can anybody please tell me if the code below is correctly written: My guess is that something is wrong in the for loop even though the code is working good.

I will appreciate any help!

code 1:

public void cloneSelectedObjects(){

SOStoupload = new List<SO_Detail__c>();


//create new OSO
Outbound_Sales_Order__c p = new Outbound_Sales_Order__c();

p.Entity__c = objectlist;
p.Buyer_Lookup__c = objectBuyer;
p.PO_Lookback__c = objectLookup;
p.OSO_creator__c=true;
insert p;


for (relatedObjects relatedObject : objectChildren)
{
    List<relatedObjectRow> selectedRelatedRows = new List<relatedObjectRow>();

    for (relatedObjectRow row : relatedObject.objectRows) 
    {
        if (row.selected)
        {
              selectedRelatedRows.add(row);
        } 
    }
    //here for loop to get values
    for (relatedObjectRow row : selectedRelatedRows) 
    {

          //create new OSDetails
                   SO_Detail__c detail = new SO_Detail__c(
                   Outbound_Sales_Order__c = p.Id,
                    NRProducts__c =String.valueof(row.obj.get('NRProduct_ID__c')),
                    Exp_Date_Override__c =Date.valueof(row.obj.get('Expiration_Date__c')),
                    Qty__c = Double.valueOf(row.obj.get('Qty_for_SOD__c'))
                    );

                   SOStoupload.add(detail);

    }
   }
  insert SOStoupload;  
 }

More code for this class:

// Get all of the children(POD) of the current (PO)
public void populateObjectChildren()
{

objectChildren = new List<relatedObjects>{};

Set<String> childObjectTypes = new Set<String>{};

// read the object types from the page parameter.    
childObjectTypes.addAll(ApexPages.currentPage().getParameters().get('childobjecttypes').split(','));

// Use the sobjecttype describe method to retrieve all 
// child relationships for the object to be cloned.    
 Schema.DescribeSObjectResult headDescribe = headsObject.getSObjectType().getDescribe();

 List<Schema.ChildRelationship> childRelationships =   headDescribe.getChildRelationships(); 

// Iterate through each relationship, 
// and retrieve the related objects.       
for (Schema.ChildRelationship childRelationship : childRelationships)
{
  Schema.SObjectType childObjectType =   childRelationship.getChildSObject();

  // Only retrieve the objects if their type is 
  // included in the page argument.          
  if (childObjectTypes.contains( childObjectType.getDescribe().getName()))
  {
    List<relatedObjectRow> relatedObjects = new List<relatedObjectRow>{};


    Schema.SObjectField childObjectField =  childRelationship.getField();

    //query for the childObject in this case the POD        
    String relatedChildSObjectsquery = 
           'SELECT id, NRProduct_ID__c,NRCode__c,Qty_for_SOD__c, Qty_Received__c, Name,Expiration_Date__c FROM ' 
         + 'Purchase_Order_Details__c'
         + ' WHERE '
         + childObjectField.getDescribe().getName()
         + ' = \'' 
         + headsObject.Id
         + '\''; 


    for (SObject childObject :  Database.query(relatedChildSObjectsquery))
    {
      relatedObjects.add(new relatedObjectRow(childObject));
    }

    if (!relatedObjects.isEmpty())
    {
      objectChildren.add(new relatedObjects(relatedObjects, 
            childObjectType.getDescribe().getLabelPlural(), 
            childObjectField.getDescribe().getName()));
       }  
     }
   }
 }

test class:

  @istest
  private class ClonePlus_Test {

   static testmethod void testcloneplus () {
  Profile p = [select id from profile where name='Standard User'];
     User ucloneplus = new User(alias = 'standt', email='standarduser@testorg.com',emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                       localesidkey='en_US', profileid = p.Id,timezonesidkey='America/Los_Angeles', username='cscloneplus@net.com');


  //Create a test account record to create a test product.
    Account aaaa = new Account(Name = 'Test Account');
    insert aaaa;

    //Create a test product to use with the order items.
    NRProducts__c pppp = new NRProducts__c(Account__c = aaaa.Id);
    insert pppp;

    Purchase_Order__c po = new Purchase_Order__c(Account__c= aaaa.id,Buyer_Lookup__c =ucloneplus.id, Specialist_Lookup__c=ucloneplus.id );
    insert new Purchase_Order__c []{po  };

    Purchase_Order_Details__c pod = new Purchase_Order_Details__c (Purchase_Order__c=po.Id , NRProducts__c = pppp.id, Expiration_Date__c=Date.valueof('2014-05-17'));
    insert new Purchase_Order_Details__c []{pod  };

    Entity__c ent = new Entity__c(name='Carlos') ;
    insert new Entity__c []{ent}; 

    String val =  'SELECT Name FROM Entity__c'
                                + ' WHERE Id = \''
                                + ent.id
                                + '\'';

    SObject headSObject5 = Database.query(val);
    String  objectEntity = '' + headSObject5.get('Name');  

    System.debug('entity: '+objectEntity);        

   Outbound_Sales_Order__c oso = new Outbound_Sales_Order__c(Entity__c= ent.id, OSO_creator__c=true);
   insert new Outbound_Sales_Order__c []{oso};   

   String val2 =  'SELECT Name FROM Outbound_Sales_Order__c'
                                + ' WHERE Id = \''
                                + oso.id
                                + '\'';

    SObject headSObject6 = Database.query(val2);
    String  objectName = '' + headSObject6.get('Name'); 

    System.debug('oso name: ' + objectName );        

    SO_Detail__c detail = new SO_Detail__c(Outbound_Sales_Order__c = oso.id, NRProducts__c = pppp.id, Qty__c = Double.valueOf('25'), Exp_Date_Override__c=Date.valueof('2014-05-17') );
    insert new SO_Detail__c []{detail}; 

  Test.startTest();
  system.runAs(ucloneplus){

  PageReference tpageRef = Page.ClonePlus;

  Test.setCurrentPage(tpageRef);

 //Set Parameters that would be passed in 
 ApexPages.currentPage().getParameters().put('Id', po.Id);
 ApexPages.currentPage().getParameters().put('childobjecttypes',  'Purchase_Order_Details__c');


 ApexPages.currentPage().getParameters().put('list',objectEntity);
 ApexPages.currentPage().getParameters().put('name',objectName );

 System.assertEquals( po.id,ApexPages.currentPage().getParameters().get('Id'));
 System.assertEquals( 'Purchase_Order_Details__c',ApexPages.currentPage().getParameters().get('childobjecttypes'));
System.assertEquals( objectEntity, ApexPages.currentPage().getParameters().get('list'));
 System.assertEquals( objectName  ,ApexPages.currentPage().getParameters().get('name'));


// Instantiate a new controller with all parameters in place
ClonePlusController pcp = new ClonePlusController();

pcp.message=pcp.msg;
pcp.debugSoql=pcp.objectlist  ;
pcp.debugSoql2= pcp.objecttext ; 

pcp.initialiseObjectsForCloning();

System.assertEquals(pcp.msg ,pcp.message);
System.assertEquals(pcp.objectlist,pcp.debugSoql);
System.assertEquals(pcp.objecttext,pcp.debugSoql2);



pcp.runSearch();
pcp.runSearch2();
pcp.cloneSelectedObjects();
pcp.cloneSelectedObjects2();
pcp.doClone();
}
Test.stopTest();

}
}
6
  • Can you post the code for your test method? – Caspar Harmer Aug 4 '14 at 19:09
  • Related: Too many SOQL queries, How to avoid Too Many SOQL Queries – user6861 Aug 4 '14 at 19:17
  • @Snowman This one isn't as obvious – EricSSH Aug 4 '14 at 19:32
  • @EricSSH that is why I said "related" and not "possible dupe of" I am just trying to provide some links to other questions that might help. – user6861 Aug 4 '14 at 19:35
  • I have updated my question, with the test class. Sorry if the test class is a mess. still learning :) – Carlos Aug 4 '14 at 20:07
2

From not reading thoroughly:

Your insert is occurring in the first of two for loops.

Try moving the insert out of the first for loop:

for (relatedObjects relatedObject : objectChildren){
    List<relatedObjectRow> selectedRelatedRows = new List<relatedObjectRow>();

    for (relatedObjectRow row : relatedObject.objectRows){
        ...
    } 
}
insert SOStoupload;

Update

Der, the issue is "Too Many SOQL Queries" rather than a "DML Issue" though the problem/solution is very similar between the two issues:

The Too Many SOQL Queries exception usually occurs when SOQL is being called in a for loop (unless you actually have 100+ "hard-coded" SOQL queries . . .). Try going through your code and note exactly where all your SOQL queries are called. I suspect you'll find one in a for loop, and then adjust accordingly.

BEWARE -- Be AWARE that methods you are using in your code might be calling SOQL queries. Make sure you know where your methods have been 0_0

14
  • It is actually out of the first loop – Carlos Aug 4 '14 at 20:01
  • Are you sure? It looks like the insert is inside the for loop that starts on line one -"for (relatedObjects relatedObject : objectChildren)". – Jagular Aug 4 '14 at 20:22
  • I mistakenly read "Too Many SOQL Queries" exception as "DML Exception" (though the remedy is the same). Check out my update. – Scott Pelak Aug 4 '14 at 20:23
  • 1
    The formatting is off - I thought that too, but if you line the braces up, it's outside any loops – Caspar Harmer Aug 4 '14 at 20:23
  • 1
    Where / What line the "Too many SOQL Queries" exception occurring? Is it in between "Test.startTest()" and "Test.stopTest()"? If so, that would imply the exception is being thrown in your Operational Code rather than the Test Code since any code between Test.startTest() and Test.stopTest() has its own Execution Context. – Scott Pelak Aug 4 '14 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.