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
Jason Kuzmak 12Jason Kuzmak 12 

Can my if statement check if a variable exists at all?

Hi All, 

I'm pretty new to coding, so this may be a really basic question.
I'm trying to modify an Apex class that was created by our original SF org developers. There is a bulk test in one of the classes that fails to pass the governor limits, I assume, because of all of the SOQL queries :
 
private class Test_OpportunityTrigger {

    static testMethod void testOpportunityTriggers()
    {
    	Test_OpportunityTrigger.testOpportunityTriggersHelper(2);
    }

    static testMethod void testOpportunityTriggersBulk()
    {
        Test_OpportunityTrigger.testOpportunityTriggersHelper(200);
    }
    
    static void testOpportunityTriggersHelper(Integer numberOfRecords)
    {
        // find a status for a converted lead
    	LeadStatus convertStatus = [
        	SELECT MasterLabel
        	FROM LeadStatus
        	WHERE IsConverted = true
        	LIMIT 1
        ];
    	
        // create leads
        List<Lead> leadList = TestData.generateLeads(numberOfRecords);
        for(Lead lead : leadList)
        {
            lead.State = 'PA';
        	lead.Stage__c = 'Sales Qualified Lead';
        	lead.Status = 'Working - Contacted';
        	lead.SIC_Code__c = 'siccode';
            lead.Branch_Code__c = '101: Corrugated Products';
        }
        insert leadList;
// convert the leads
        List<Database.LeadConvert> leadConvertList = new List<Database.LeadConvert>();
        for(Integer ii=0; ii<leadList.size(); ++ii)
        {
            Lead lead = leadList[ii];
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setLeadId(lead.Id);
            lc.setConvertedStatus(convertStatus.MasterLabel);
            leadConvertList.add(lc);
        }
        
        if(!leadConvertList.isEmpty()){
            List<Database.LeadConvertResult> lcrList = Database.convertLead(leadConvertList);
        }
        
        // build a map to correlate an opportunity and contact for role verification
        Map<Id, Id> opportunityToContactMap = new Map<Id, Id>();
        List<OpportunityContactRole> oppConRoleSOQL = [SELECT Id, OpportunityId, ContactId FROM OpportunityContactRole WHERE IsPrimary = true AND Role = 'Decision Maker'];
        for(OpportunityContactRole opportunityContactRole : oppConRoleSOQL){
            opportunityToContactMap.put(opportunityContactRole.OpportunityId, opportunityContactRole.ContactId);
        }
        
        // verify that the lookup was populated on the opportunity and that the opportunity contact roles were created
        


        Map<Id, Contact> oppIdToContactMap = new Map<Id, Contact>();
        Map<Id, Contact> contactMap = new Map<Id, Contact>([SELECT Id, AccountId FROM Contact]);
        List<Opportunity> opportunityList = [SELECT Id, AccountId, Opportunity_Contact__c FROM Opportunity];

        


        for(Opportunity opportunity : opportunityList)
        {
            Contact contact = contactMap.get(opportunity.Opportunity_Contact__c);
            System.assertEquals(opportunity.AccountId, contact.AccountId);
            System.assertEquals(opportunityToContactMap.get(opportunity.Id), opportunity.Opportunity_Contact__c);
        }
        
        // insert new contacts and change the opportunity contact
        List<Contact> contactList = TestData.generateContacts(numberOfRecords);
        for(Integer ii=0; ii<contactList.size(); ++ii){
            contactList[ii].AccountId = opportunityList[ii].AccountId;
        }
        insert contactList;
        for(Integer ii=0; ii<opportunityList.size(); ++ii){
            opportunityList[ii].Opportunity_Contact__c = contactList[ii].Id;
        }
        update opportunityList;
        
        // verify that the contact roles were updated
        opportunityToContactMap.clear();
        // JKK created this line too. Same as above.
        oppConRoleSOQL = [SELECT Id, OpportunityId, ContactId FROM OpportunityContactRole WHERE IsPrimary = true AND Role = 'Decision Maker'];
        for(OpportunityContactRole opportunityContactRole : oppConRoleSOQL){
            opportunityToContactMap.put(opportunityContactRole.OpportunityId, opportunityContactRole.ContactId);
        }
        for(Integer ii=0; ii<opportunityList.size(); ++ii)
        {
            Opportunity opportunity = opportunityList[ii];
            System.assertEquals(opportunityToContactMap.get(opportunity.Id), opportunity.Opportunity_Contact__c);
        }
    }
}


So, I can cause this to pass just by changing the Bulk trigger value from 200 to like, 10. What I would PREFER to do, is just run an if statement for the SOQL variables that says "if this variable already exists, don't run this query for it." If I just test for whether the variable is 'null', it'll just say that the variable doesn't exist. Well shoot, THAT'S what I'd like to test for, then! If it doesn't exist, do a thing! Or, will that not solve my governor limit problem?

Any ideas?

Jason Kuzmak 12Jason Kuzmak 12
Update! So I take it back; I can't make my class pass the test by changing that 200 to a 10. I also wanted to share the error that was popping when I try to run this class:

Test_OpportunityTrigger
testOpportunityTriggersBulk
System.DmlException: ConvertLead failed. First exception on row 37; first error: UNKNOWN_EXCEPTION, System.LimitException: Too many SOQL queries across namespaces: 1101 Class.OpportunityTriggerHandler.handleBeforeInsert: line 15, column 1 Trigger.OpportunityTrigger: line 15, column 1: [] 
Stack Trace: Class.Test_OpportunityTrigger.testOpportunityTriggersHelper: line 52, column 1 Class.Test_OpportunityTrigger.testOpportunityTriggersBulk: line 14, column 1
Jyosi jyosiJyosi jyosi
Hello Jason,

Based on the undersatding you are firing the trigger from Opportunity.
Bascially  we need to change the Trigger context variable .
In trigger you can change the code
OpportunityTrigger  Opty= new OpportunityTrigger ();
If(Trigger.IsInsert && Trigger.IsBefore)
{
Opty.testOpportunityTriggersHelper(Trigger.new);
}
 Public void testOpportunityTriggersHelper(List<Opporunity >numberOfRecords)
{
  Try to get the list of opty ID and get the values of Leads and opportunityContactRole and insert and update accordingly
}

Please let me know if you have any question.

Thanks

Regards,
Jyo
Jason Kuzmak 12Jason Kuzmak 12
Hi Jyo, 

Thanks! But I'm a little confused what part you're referencing. The code I provided above is a test class, and I'm trying to understand what's making it reach its governor limits. Maybe we should start with that. Can you point anything out (and describe) to me from the code I provided what looks like it might be causing the error?
Jyosi jyosiJyosi jyosi
Hello Jason,

Can i get the trigger and handler class code .

Thanks

Regards,
Jyo
Jason Kuzmak 12Jason Kuzmak 12
Hi Jyo, 

The Handler Class is here:
 
public with sharing class OpportunityTriggerHandler {
  
  public static void handleBeforeInsert()
  {
    // build a map of opportunities created due to lead conversion, indexed by account ID
    Map<Id, Opportunity> accountIdToOppmap = new Map<Id, Opportunity>();
    for(Opportunity opportunity : (List<Opportunity>)trigger.new)
    {
      if(opportunity.Created_Via_Conversion__c == true){
        accountIdToOppmap.put(opportunity.AccountId, opportunity);
      }
    }
    
    // find the contacts to associate with the opportunities (there will only be 1 contact for each account created by lead conversion)
    for(Contact contact : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIdToOppmap.keySet()])
    {
      Opportunity opportunity = accountIdToOppmap.get(contact.AccountId);
      if(opportunity != null){
        opportunity.Opportunity_Contact__c = contact.Id;
      }
    }
  }
  
  public static void handleAfterInsert()
  {
    OpportunityService.updatePrimaryContactRoles(Trigger.new);
  }
  
  public static void handleAfterUpdate()
  {
    // find out which opportunities had their contact changed
    List<Opportunity> opportunityList = new List<Opportunity>();
    for(Opportunity opportunity : (List<Opportunity>)Trigger.new)
    {
      Opportunity oldOpportunity = (Opportunity)Trigger.oldMap.get(opportunity.Id);
      if(opportunity.Opportunity_Contact__c != oldOpportunity.Opportunity_Contact__c){
        opportunityList.add(opportunity);
      }
    }
    
    if(!opportunityList.isEmpty()){
      OpportunityService.updatePrimaryContactRoles(opportunityList);
    }
  }

}

And Here is the opportunity trigger:
 
trigger OpportunityTrigger on Opportunity (after delete, after insert, after undelete, after update, before delete, before insert, before update) {
  
  if(Trigger.isAfter)
  {
    if(Trigger.isInsert){
      OpportunityTriggerHandler.handleAfterInsert();
    }
    else if(Trigger.isUpdate){
      OpportunityTriggerHandler.handleAfterUpdate();
    }
  }
  else
  {
    if(Trigger.isInsert){
      OpportunityTriggerHandler.handleBeforeInsert();
    }
  }

}