apex-enterprise-patterns / fflib-apex-mocks

An Apex mocking framework for true unit testing in Salesforce, with Stub API support
BSD 3-Clause "New" or "Revised" License
423 stars 214 forks source link

feat: support setReadOnlyFields by FieldName #129

Closed sbresin closed 2 years ago

sbresin commented 2 years ago

What does this implement/fix? Explain your changes.

When trying to mock a SObject with parent record fields from a polymorphic relationship, i can't set these using fflib_ApexMocksUtils.setReadOnlyFields()

Example query i want to mock:

SELECT Id, Subject, TYPEOF What WHEN Account THEN Id, Name END FROM Task

Trying this:

Account acc = new Account(Name='TestAccount');
Task t = new Task(
  What = acc
);

results in: Field is not writeable: Task.What

fflib_ApexMocksUtils.setReadOnlyFields() only allows to set readonly fields using a Map<SObjectField, Object>, which does not help in this case.

So this PR adds a new overload setReadOnlyFields(SObject objInstance, Type deserializeType, Map<String, Object> properties), which allows me to do this, using strings instead of SObjectField:

Task t = (Task)fflib_ApexMocksUtils.setReadOnlyFields(
  new Task(Subject='TestTask'),
  Task.class,
  new Map<String, Object> {'What' => acc}
);

This change is Reviewable

ImJohnMDaniel commented 2 years ago

@sbresin, thanks for the submission!