2

I am trying to add records to Opportunity.OpportunityLineItems; however, I got an error that that field is read-only. I tried to mock that field via fflib, code as follows:

fflib_ApexMocks mocks = new fflib_ApexMocks();

Opportunity opportunityMock1 = new Opportunity(Id = fflib_IDGenerator.generate(Opportunity.SObjectType));

mocks.startStubbing();
mocks.when(opportunityMock1.OpportunityLineItems).thenReturn(new List<OpportunityLineItem>{
        new OpportunityLineItem(Id = fflib_IDGenerator.generate(OpportunityLineItem.SObjectType)),
        new OpportunityLineItem(Id = fflib_IDGenerator.generate(OpportunityLineItem.SObjectType))
});
mocks.stopStubbing();

After mocking the opportunity opportunityMock1.OpportunityLineItems it returns null. Do you know what am I doing wrong? or maybe a different way to add items to opportunityMock1.OpportunityLineItems?

1 Answer 1

4

I learnt that the way to mock a related list of an object in fflib is by using the method fflib_ApexMocksUtils.makeRelationship.

Solution:

fflib_ApexMocks mocks = new fflib_ApexMocks();

Opportunity opportunityMock1 = new Opportunity(Id = fflib_IDGenerator.generate(Opportunity.SObjectType));

List<Opportunity> opportunitiesWithProductsMock = (List<Opportunity>) fflib_ApexMocksUtils.makeRelationship(
        List<Opportunity>.class,
        new List<Opportunity>{
                opportunityMock1
        },
        OpportunityLineItem.OpportunityId,
        new List<List<OpportunityLineItem>>{
                new List<OpportunityLineItem>{
                        new OpportunityLineItem(Id = fflib_IDGenerator.generate(OpportunityLineItem.SObjectType)),
                        new OpportunityLineItem(Id = fflib_IDGenerator.generate(OpportunityLineItem.SObjectType))
                }
        }
);
3
  • 3
    this is correct but I found the syntax messy and switched to using SObject Fabricator and never looked back - syntax so much clearer
    – cropredy
    Aug 4, 2020 at 19:16
  • I had a look to the repo, it is great!. Thanks a lot. Aug 4, 2020 at 20:41
  • 1
    Pro tip: in sfab, relationship names are case sensitive
    – cropredy
    Aug 4, 2020 at 21:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .