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
Gabriel Corrêa de OliveiraGabriel Corrêa de Oliveira 

Can't create bidirectional Partner in test setup

When I add a partner to an opportunity through the web UI and issue a query like this:
[select AccountFromId, AccountToId, Role, OpportunityId, ReversePartnerId from Partner where OpportunityId = :opportunityId]

Two records are found. One has the AccountFromId field referring to the opportunity's account and AccountToId referring to the partner account while the other one has AccountToId referring to the opportunity's account and AccountFromId referring to the partner account.

Both also have the ReversePartnerId field referring to one another; and, thus, form some kind of bidirectional relationship.

I have some APEX code that queries the Partner object to find which accounts are related to a certain opportunity. Hence, I need to write test cases that setup the right database environment before they run. I want to run them with @isTest(seeAllData=false), for they need to be deterministic and not affected by the state of the production database when I deploy them.

I tried the following:
Partner partner = new Partner();
partner.AccountToId = partnerAccountId;
partner.OpportunityId = opportunityId;
partner.IsPrimary = true;
partner.Role = PARTNER_ROLE; // A constant
insert partner;
I ran this from the @testSetup method, but only one record was inserted.

Then, I  tried to insert the reverse relationship record programmatically in many different ways, but Salesforce doesn't allow us to set AccountFromId and OpportunityId at the same time. In addition, the  ReversePartnerId field is not writable.

My conclusion so far is that it's impossible to create the bidirectional relationships in the same way that Salesforce does when we use the web UI.

There are no clear directions in the documentation on how to insert these objects, and this seems to be yet another pitfall in Salesforce's CRM platform.
Is it working in normal Apex class?