Relationship returning null in unit test

In a unit test, I’m having a problem where values spanning relationships are blank. I have a custom field, Quote.My_Formula_Field__c, which is defined as Opportunity.Lookup__r.Name, which is used in a validation rule. This always returns null in my unit test.

Test code snippet:

Opportunity testOpp = new Opportunity(
  Name = 'Test Opp',
  AccountId = testAccount1.Id,
  CloseDate = system.today(),
  StageName = 'Open',
  Lookup__c = testAccount2.Id,
  Pricebook2Id = test.getStandardPricebookId());
insert testOpp;

Quote testQuote = new Quote(
  name = 'Test Quote',
  OpportunityId = testOpp.Id,
  Pricebook2Id = test.getStandardPricebookId(),
  Status = 'Open');
insert testQuote;

testQuote = [SELECT Id, OpportunityId, Opportunity.Lookup__c 
             FROM Quote WHERE Id=:testQuote.Id];


System.debug('Quote.Opp: ' + testQuote.OpportunityId); // testOpp.Id  
System.debug('Opp.Lookup__c:'  : testOpp.Lookup__c); // Lookup__c
System.debug('Quote.Opp.Lookup__c:'  : testQuote.Opportunity.Lookup__c); // null  

Similar questions:

Test data fields return null in class but are populated in unit test

Why is my reference field returning null my test code?

** Update **

I added the following two assertions:

// This assertion passes
System.assertEquals(testOpp.Id, testQuote.OpportunityId, 'Opportunity does not match.');
// This assert fails; expected NULL, actual [record id]
System.assertEquals(testQuote.Opportunity.Lookup__c, testOpp.Lookup__c, 'Lookup__c does not match.');

Answer

I’ve tried to reproduce your problem using some added fields in an org and this test:

@isTest
private class MyTest {

    @isTest
    static void test() {

        Account testAccount1 = new Account(Name = 'a1');
        insert testAccount1;
        Account testAccount2 = new Account(Name = 'a2');
        insert testAccount2;

        Opportunity testOpp = new Opportunity(
          Name = 'Test Opp',
          AccountId = testAccount1.Id,
          CloseDate = system.today(),
          StageName = 'Open',
          Lookup__c = testAccount2.Id,
          Pricebook2Id = test.getStandardPricebookId());
        insert testOpp;

        Quote testQuote = new Quote(
          name = 'Test Quote',
          OpportunityId = testOpp.Id,
          Pricebook2Id = test.getStandardPricebookId(),
          Status = 'Open');
        insert testQuote;

        testQuote = [SELECT Id, OpportunityId, Opportunity.Lookup__c, My_Formula_Field__c
                     FROM Quote WHERE Id=:testQuote.Id];

        System.assertNotEquals(null, testQuote.Opportunity);
        System.assertNotEquals(null, testQuote.Opportunity.Lookup__c);
        System.assertNotEquals(null, testQuote.My_Formula_Field__c);
    }
}

but the test passes so the problem is in something other than the code posted in the question.

Attribution
Source : Link , Question Author : Mike Chale , Answer Author : Keith C

Leave a Comment