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
Stuart GrimshawStuart Grimshaw 

How do I add data to a Lookup field when generating data for unit tests?

I have a class that I'm using to load data in to the database for my unit tests & I'm trying to populate a Lookup field with some data.

The Lookup field is on a User, and the field is a custom one I added to Product2.

I'm trying to assign the user like this:

  User u = [SELECT Id from User WHERE email = 'stuart.grimshaw@workemail.com'];

  Product2 withTraining = new Product2(Name='Product with Bundled Support & Training', Support_Level__c = 'Silver', Support_Email_Body__c = 'All the things!', Support_Contacts__c = 2, Server_License_Count__c = 5, User_License_Count__c = 15, Product_Type__c = 'Product, Support & Training Bundle');
  withTraining.Trainer__c = u.Id;

or this:

  Product2 withTraining = new Product2(Name='Product with Bundled Support & Training', Support_Level__c = 'Silver', Support_Email_Body__c = 'All the things!', Support_Contacts__c = 2, Server_License_Count__c = 5, User_License_Count__c = 15, Product_Type__c = 'Product, Support & Training Bundle', Trainer__c =u.Id);

or this:

  Product2 withTraining = new Product2(Name='Product with Bundled Support & Training', Support_Level__c = 'Silver', Support_Email_Body__c = 'All the things!', Support_Contacts__c = 2, Server_License_Count__c = 5, User_License_Count__c = 15, Product_Type__c = 'Product, Support & Training Bundle', Trainer__r =u);

None of these things seems to work, when I try and retreive the name of trainer in my test like this:

    public String getTrainerName() {
        if(this.quoteProds == null) {
            this.quoteProds = getQuoteLineItems(this.quoteId);
        }

        for (QuoteLineItem lineItem : this.quoteProds) {
            if(lineItem.PricebookEntry.Product2.Trainer__r.Id  != null) {
                return lineItem.PricebookEntry.Product2.Trainer__r.Name;
            }
        }

        return 'Unknown';
    }

I get 'Unkown'.

Other tests in the suite confirm that the Quote does have line items.
splitthebills1.3947274848456084E12splitthebills1.3947274848456084E12
The first 2 are identical and should work, the 3rd will never work.