2

Hi Everyone I'd like to post my very first question on Salesforce Apex and ask for any help on this. What I'm looking for here is guidance on how to proceed on querying data from OpportunityLineItem Object programmatically.

My end goal is to copy a value from a custom field under Product to a custom text field in Opportunity. During my research I got to know that the link between Opportunity and Product happens through OpportunityLineItems which links the two Obejects. (This is my understanding based on googling stuff)

In the code below I'm setting the values for OpportunityLineItems - OpportunityId and Product2ID in a way that I'd know it was working for the scenario I have. Here's the code to list Opportunities with Product with Practice field(at least it was the plan...):

public with sharing class UpdatePracticeOnOpportunity {
    //Method to get opportunities that have products associated to it
    public List<OpportunityLineItem> getAllOppsWithPractice() {
      String OppId =    '0064x0000037gMqAAI';
      String Prod2Id =  '01t4x00000164W8AAI';

      //Receives OLIS values 
      List<OpportunityLineItem> OppWithPractice = new List<OpportunityLineItem>([SELECT id, name, OpportunityId, Product2Id
                                                                                FROM OpportunityLineItem]);
                                                  // WHERE PRODUCT2.ID = :Prod2Id AND OPPORTUNITY.ID = :OppId
       
        return OppWithPractice;                
      }
}

Here's the class I'm using to run Apex Tests

@IsTest
public with sharing class UpdatePracticeOnOpportunityTest {
    @IsTest
    static void should_update_opportunity() {
      //Test.startTest();
        UpdatePracticeOnOpportunity upOppPractice = new UpdatePracticeOnOpportunity();
      //Test.stopTest();
        upOppPractice.getAllOppsWithPractice();        
  }

For some reason both queries are returning nothing, however running the same query via SOQL it does return rows. What am I missing here? This code was run in two different Orgs but had the same result.

Here's the results of a query run using SOQL on Visual Code

SELECT id, name, OpportunityId, Product2Id FROM OpportunityLineItem

|ID               |  NAME                                             |  OPPORTUNITYID    |   PRODUCT2ID
──────────────────  ─────────────────────────────────────────────────  ──────────────────  ──────────────────
|00k5A00000r6ftzQAA|  Edge Installation GenWatt Diesel 1000kW          |  0065A00000n4bIFQAY | 01t5A000008OOn3QAG
|00k5A00000r6ft6QAA|  Dickenson Mobile Generators GenWatt Diesel 1000kW|  0065A00000n4bI0QAI | 01t5A000008OOn3QAG

Running code as SFDX: Execute Anonymous Apex with Currently Selected Text

19:24:00.11 (19609255)|VARIABLE_ASSIGNMENT|[3]|OppWithPractice|[{"Id":"00k4x00000gD7zrAAC","Name":"Burlington Textiles  (45 more) ...","OpportunityId":"0064x0000037gMqAAI","Product2Id":"01t4x00000164W8AAI"}]|0x6e0f8062
19:24:00.19 (19688432)|CUMULATIVE_LIMIT_USAGE
19:24:00.19 (19688432)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 1 out of 100
  Number of query rows: 1 out of 50000

References:

4
  • 2
    This sort of apparent inconsistency is usually due to using a different contextual user with different sharing access to records. Are you running the SOQL and Apex using the same login? Is your Apex "with sharing"?
    – Phil W
    Mar 29, 2021 at 22:06
  • Hi @PhilW, thank you for your response. Both SOQL and Apex are using the same login. What do you mean by "with sharing" would that be something like this: public with sharing class UpdatePracticeOnOpportunity {
    – Tom Souza
    Mar 29, 2021 at 22:41
  • 1
    are you calling your apex in a testmethod? that would produce no results as testmethods won't normally be able to see live data
    – cropredy
    Mar 30, 2021 at 1:47
  • @cropredy, yes I'm calling it from a test method. Updated the description with that part of the code as well. I'm using Visual Code and can see some data when running SFDX: Launch Apex Replay Debugger with Current File like variables under Variables > Local for some reason it made me believe that it would show there the query values. Another point is that even when running normal Apex Tests I see the following under the results: Number of SOQL queries: 1 out of 100 Number of query rows: 0 out of 50000
    – Tom Souza
    Mar 30, 2021 at 2:49

1 Answer 1

5

When you use a testmethod, no org data records are available for querying (some exceptions like setup objects: User, Profile, UserRole, StaticResource, etc)

So, the testmethod has to mock the data for the code under test to execute as expected

static void should_update_opportunity() {
      // Given mock Products
      Product2[] mockProducts = new List<Product2> {
          new Product2(..),
          ...
      };
      insert mockProducts

      // Given mockPricebookEntries
      ...
      // Given Mock Accounts
      ...
      // Given Mock Opportunities
      ...
      // Given Mock OpportunityLineItems
      ... 

      // When code to be tested invoked ...
      Test.startTest();
        UpdatePracticeOnOpportunity upOppPractice = new UpdatePracticeOnOpportunity();
       OpportunityLineItem[] results =  upOppPractice.getAllOppsWithPractice();
       Test.stopTest();

      // Then verify results
      System.assertEquals(...);        
  }

Now, if you are just trying to see if your code works because you are learning, you can use execute anonymous apex which will run against the org's data records

2
  • thank you for explaining that part, I wasn't fully aware of. I've added System.debug(o) in my code to see some of the values and it gave me an idea of what was happening internally. Bc of my misunderstanding, I was trying to see the variables in real-time in Visual Code to make sure the right values were pulled from SF Objects, as you've mentioned running as anonymous showed me the values I was expecting to see. In the end I've took a different approach that will be shared as an answer to my own question, maybe it can help others going through this issue.
    – Tom Souza
    Mar 31, 2021 at 2:41
  • Here's a link to another post talking about which approach I end up taking: salesforce.stackexchange.com/questions/339275/…
    – Tom Souza
    Apr 2, 2021 at 2:12

You must log in to answer this question.

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