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

Add a method to allow us to create any SObjects with any NON WRITABLE Field #123

Closed AllanOricil closed 3 years ago

AllanOricil commented 3 years ago

I found a use case that is not coverade by fflib_ApexMocksUtils.makeRelationship()

I had to create a ContentDocument with the field LatestPublishedVersionId filled in, and I couldnt.

When I tried the code below, I got this error: Field is not writeable: ContentDocument.LatestPublishedVersionId

ContentDocument cd = new ContentDocument(
Id = fflib_IDGenerator.generate(Schema.ContentDocument.SObjectType),
LatestPublishedVersionId =  fflib_IDGenerator.generate(Schema.ContentVersion.SObjectType)
);

To get over it, I used the same strategy implemented by fflib_ApexMocksUtils.makeRelationship but I did not write a cool serializer. I just typed in the json and bound the values I needed on it.

The result is the code below :D

ContentDocument contentDocument = (ContentDocument) JSON.deserialize('{"attributes":{"type":"ContentDocument","url":"/services/data/v52.0/sobjects/ContentDocument/' + documentSignignRequest.Id + '"},"Id":"' + documentSignignRequest.Id + '","LatestPublishedVersionId":"' + fflib_IDGenerator.generate(Schema.ContentVersion.SObjectType) + '","ParentId": "' + parentId + '"}', Schema.ContentDocument.class);
        System.debug(contentDocument);

I was able to create my ContentDocument with the field LatestPublishedVersionId filled in.

AllanOricil commented 3 years ago

It could follow something like the code below, that enables us to generate Objects by building a JSON, but with an Apex API

SObjectFactory.new(Schema.SObjectName.class).addField(SObjectName.FieldName, VALUE).addChildren().....

addField adds any field or reference, such as LatestPublishedVersionId addChildren adds a factory for the related object

this will enable us to create object building a JSON with an Apex API

AllanOricil commented 3 years ago

No need for this. There is a method called setReadOnlyFields which allows me to do it.