apex-enterprise-patterns / fflib-apex-common

Common Apex Library supporting Apex Enterprise Patterns and much more!
BSD 3-Clause "New" or "Revised" License
911 stars 517 forks source link

How do we Mock selectors that query Child Relationship? #375

Closed AllanOricil closed 3 years ago

AllanOricil commented 3 years ago

Could you show how would you mock a Selector method that selects Accounts and its Contacts?

Imagine that the method is called

selectAccountsByIdWithContacts(Set<Id> accountIds);

and it issues a query like the one below

SELECT Id, Name, (SELECT Id, FirstName, LastName FROM Contacts) FROM Account WHERE Id IN :accountIds

This method returns List and each account entry can access a list of Contacts called "Contacts".

Im asking it because I tried to mock another object with its children and I got this error message

Field is not writeable: DocumentSigningRequest__c.DocumentSigningRequestSigners__r

So I don't know how to mock this type of query.

wimvelzeboer commented 3 years ago

Ah yeah, mocking readonly fields in records, and related records is somewhat more difficult todo. But luckily the architect behind the framework @afawcett came up with a solution; Mock Sub-Selects

I hope that Salesforce will one day allow us to set read-only field and related records in a normal way, in the context of a unit-test of course.

AllanOricil commented 3 years ago

FFlib Apex Mocks has this method implemented in case anybody else need to this:

fflib_ApexMocksUtils.makeRelationship

AllanOricil commented 3 years ago

@wimvelzeboer I used it, and it did not work for my use case. Look what I wrote here: https://github.com/apex-enterprise-patterns/fflib-apex-mocks/issues/122

AllanOricil commented 3 years ago

Just because I posted it here, it worked hahaha