简体   繁体   English

Salesforce APEX - 测试上下文为相关对象返回null

[英]Salesforce APEX - Test context returning null for related objects

When writing a testMethod I am unable to retrieve related contact fields. 编写testMethod时,我无法检索相关的联系人字段。 In the example below I would expect the final assert to return true. 在下面的示例中,我希望最终的断言返回true。 The code I am testing works fine, the select is only failing in a testing context. 我正在测试的代码运行正常,select只在测试环境中失败。

Why is the Contact info no being returned from the SOQL query? 为什么不从SOQL查询返回联系信息?

static testMethod void FailTest()
{
        Contact client = new Contact(FirstName='TestFirst1', LastName='TestFirst', BirthDate = Date.parse('01/01/1986'), Gender__c = 'Male');
        insert client;
        Opportunity opp = new Opportunity(Name = 'Test Opp' + Math.random(), CloseDate=Date.Today(), StageName='ASR - Case Design', Product_Types__c='UL', Face_Amount_Applied_For__c=500, Estimated_Target_Premium__c=1000, X1st_Client__r = client);
        insert opp;

        Opportunity selectOpp = [Select o.X1st_Client__r.LastName From Opportunity o WHERE o.Id = :opp.Id LIMIT 1];

        system.assertNotEquals(opp.X1st_Client__r.LastName, null); //true
        system.assertNotEquals(opp.Name, null); //true
        system.assertNotEquals(selectOpp.Name, null); //true
        system.assertNotEquals(selectOpp.X1st_Client__r.LastName, null); //false, should be true
}

I think the issue could be the way you are associating the opportunity to the client record. 我认为问题可能是您将机会与客户记录相关联的方式。 You have X1st_Client__r = client and I think what you might really want to do is X1st_Client__c = client.Id. 你有X1st_Client__r =客户端,我认为你真正想要做的是X1st_Client__c = client.Id。 I don't think an insert DML will take into account the object represented in X1st_Client__r. 我不认为插入DML会考虑X1st_Client__r中表示的对象。 I think it will only pay attention to the X1st_Client__c value during an insert. 我认为在插入过程中只会注意X1st_Client__c值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM